repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rustedivan/tapmap
|
geobaketool/Operations/OperationFixupHierarchy.swift
|
1
|
3513
|
//
// OperationFixupHierarchy.swift
// geobakeui
//
// Created by Ivan Milles on 2018-10-22.
// Copyright © 2018 Wildbrain. All rights reserved.
//
import Foundation
class OperationFixupHierarchy : Operation {
let continentList : ToolGeoFeatureMap
let countryList : ToolGeoFeatureMap
let provinceList : ToolGeoFeatureMap
var output : ToolGeoFeatureMap?
let report : ProgressReport
init(continentCollection: ToolGeoFeatureMap,
countryCollection: ToolGeoFeatureMap,
provinceCollection: ToolGeoFeatureMap,
reporter: @escaping ProgressReport) {
continentList = continentCollection
countryList = countryCollection
provinceList = provinceCollection
report = reporter
output = [:]
super.init()
}
override func main() {
guard !isCancelled else { print("Cancelled before starting"); return }
// Collect provinces into their countries
var remainingProvinces = Set(provinceList.values)
var geoCountries = ToolGeoFeatureMap()
let numProvinces = remainingProvinces.count
for (key, country) in countryList {
// Countries consist of their provinces...
let belongingProvinces = remainingProvinces.filter { $0.countryKey == country.countryKey }
// ...and all the larger places in those provinces
let belongingPlaces = Set(belongingProvinces
.flatMap { $0.places ?? [] }
.filter { $0.kind != .Town } // Don't promote towns and region labels
.filter { $0.kind != .Region }
)
var updatedCountry = country
updatedCountry.children = belongingProvinces
updatedCountry.places = (country.places ?? Set()).union(belongingPlaces)
geoCountries[key] = updatedCountry
remainingProvinces.subtract(belongingProvinces)
if (numProvinces > 0) {
report(1.0 - (Double(remainingProvinces.count) / Double(numProvinces)), country.name, false)
}
}
report(1.0, "Collected \(numProvinces - remainingProvinces.count) provinces into \(geoCountries.count) countries", true)
// Collect countries into their continents
var remainingCountries = Set(geoCountries.values)
var geoContinents = ToolGeoFeatureMap()
let numCountries = remainingCountries.count
for (key, continent) in continentList {
let belongingCountries = remainingCountries.filter { $0.continentKey == continent.continentKey }
let belongingPlaces = Set(belongingCountries
.flatMap { $0.places ?? [] }
.filter { $0.kind == .Capital }
)
var updatedContinent = continent
updatedContinent.children = belongingCountries
updatedContinent.places = (continent.places ?? Set()).union(belongingPlaces)
geoContinents[key] = updatedContinent
remainingCountries.subtract(belongingCountries)
if (numCountries > 0) {
report(1.0 - (Double(remainingCountries.count) / Double(numCountries)), continent.name, false)
}
}
report(1.0, "Collected \(geoCountries.count) countries into \(geoContinents.count) continents", true)
output = geoContinents
report(1.0, "Assembled completed world.", true)
print(" - Continent regions: \(continentList.count)")
print(" - Country regions: \(countryList.count)")
print(" - Province regions: \(provinceList.count)")
if !remainingCountries.isEmpty {
print("Remaining countries:")
print(remainingCountries.map { "\($0.name) - \($0.continentKey)" })
}
if !remainingProvinces.isEmpty {
print("Remaining provinces:")
print(remainingProvinces.map { "\($0.name) - \($0.countryKey)" })
}
print("\n")
}
}
|
mit
|
cdcd8acb2e5210fffe451592469c913b
| 31.82243 | 122 | 0.709852 | 3.872106 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV
|
PopcornKit/Models/Episode.swift
|
1
|
9528
|
import Foundation
import ObjectMapper
import MediaPlayer.MPMediaItem
/**
Struct for managing episode objects.
**Important**: All images are `nil` unless episode was loaded from trakt. An image is obtained by calling `getEpisodeMetadata:showId:episodeNumber:seasonNumber:completion:` on `TraktManager`. Once image is obtained only the `largeBackgroundImage` variable should be set; the other two are computed and are not settable - they will be automatically updated once `largeBackgroundImage` is set.
*/
public struct Episode: Media, Equatable {
/// The date of which the episode was first aired.
public var firstAirDate: Date
/// The title of the episode. If there is no title, the string "Episode" followed by the episode number will be used.
public let title: String
/// The summary of the episode. Will default to "No summary available.".localized if there is no summary available on the popcorn-api.
public var summary: String
/// The tvdb id of the episode.
public let id: String
/// IMDB id of the episode. This will be `nil` unless explicitly set by calling `getEpisodeMetadata:showId:episodeNumber:seasonNumber:completion:` on `TraktManager` or the episode was loaded from Trakt.
public var imdbId: String?
/// TMDB id of the episode. This will be `nil` unless explicitly set by calling `getTMDBId:forImdbId:completion:` on `TraktManager` or the episode was loaded from Trakt.
public var tmdbId: Int?
/// The slug for episode. May be wrong as it is being computed from title instead of being pulled from apis.
public let slug: String
/// The season that the episode is in.
public let season: Int
/// The number of the episode in relation to the season.
public let episode: Int
/// The corresponding show object.
public var show: Show?
/// Convenience variable. Boolean value indicating the watched status of the episode.
public var isWatched: Bool {
get {
return WatchedlistManager<Episode>.episode.isAdded(id)
} set (add) {
add ? WatchedlistManager<Episode>.episode.add(id) : WatchedlistManager<Episode>.episode.remove(id)
}
}
/// If fanart image is available, it is returned with size 600*338. Will be `nil` until an image is obtained by calling `getEpisodeMetadata:showId:episodeNumber:seasonNumber:completion:` on `TraktManager`.
public var smallBackgroundImage: String? {
return largeBackgroundImage?.replacingOccurrences(of: "original", with: "w500")
}
/// If fanart image is available, it is returned with size 1000*536. Will be `nil` until an image is obtained by calling `getEpisodeMetadata:showId:episodeNumber:seasonNumber:completion:` on `TraktManager`.
public var mediumBackgroundImage: String? {
return largeBackgroundImage?.replacingOccurrences(of: "original", with: "w780")
}
/// If fanart image is available, it is returned with size 1920*1080. Will be `nil` until an image is obtained by calling `getEpisodeMetadata:showId:episodeNumber:seasonNumber:completion:` on `TraktManager`.
public var largeBackgroundImage: String?
/// The torrents for the episode. May be empty if no torrents are available or if episode was loaded from Trakt. Can be obtained by calling `getInfo:imdbId:completion` on `ShowManager`. Keep in mind the aformentioned method does not return images so `getEpisodeMetadata:showId:episodeNumber:seasonNumber:completion:` will have to be called on `TraktManager`.
public var torrents = [Torrent]()
/// The subtitles associated with the episode. Empty by default. Must be filled by calling `search:episode:imdbId:limit:completion:` on `SubtitlesManager`.
public var subtitles = Dictionary<String, [Subtitle]>()
public init?(map: Map) {
do { self = try Episode(map) }
catch { return nil }
}
private init(_ map: Map) throws {
if map.context is TraktContext {
self.id = try map.value("ids.tvdb", using: StringTransform())
self.episode = try map.value("number")
} else {
self.episode = ((try? map.value("episode")) ?? Int((map.JSON["episode"] as? String)!)!)
self.id = (((try? map.value("tvdb_id", using: StringTransform()).replacingOccurrences(of: "-", with: "")) ?? (map.JSON["tvdb_id"] as? String)?.replacingOccurrences(of: "-", with: "")) ?? "" )
if let torrents = map["torrents"].currentValue as? [String: [String: Any]] {
for (quality, torrent) in torrents {
if var torrent = Mapper<Torrent>().map(JSONObject: torrent) , quality != "0" {
torrent.quality = quality
self.torrents.append(torrent)
}
}
}
torrents.sort(by: <)
}
self.tmdbId = try? map.value("ids.tmdb")
self.imdbId = try? map.value("ids.imdb")
self.show = try? map.value("show") // Will only not be `nil` if object is mapped from JSON array, otherwise this is set in `Show` struct.
self.firstAirDate = try map.value("first_aired", using: DateTransform())
self.summary = ((try? map.value("overview")) ?? "No summary available.".localized).removingHtmlEncoding
self.season = ((try? map.value("season")) ?? Int((map.JSON["season"] as? String)!)!)
let episode = self.episode // Stop compiler complaining about passing uninitialised variables to closure.
self.title = ((try? map.value("title")) ?? "Episode \(episode)").removingHtmlEncoding
self.slug = title.slugged
self.largeBackgroundImage = try? map.value("images.fanart")
}
public init(title: String = NSLocalizedString("Unknown", comment: ""), id: String = "0000000", tmdbId: Int? = nil, slug: String = "unknown", summary: String = "No summary available.".localized, torrents: [Torrent] = [], subtitles: Dictionary<String, [Subtitle]> = [:], largeBackgroundImage: String? = nil, largeCoverImage: String? = nil, show: Show? = nil, episode: Int = -1, season: Int = -1) {
self.title = title
self.id = id
self.tmdbId = tmdbId
self.slug = slug
self.summary = summary
self.torrents = torrents
self.subtitles = subtitles
self.largeBackgroundImage = largeBackgroundImage
self.firstAirDate = .distantPast
self.show = show
self.season = season
self.episode = episode
}
public mutating func mapping(map: Map) {
switch map.mappingType {
case .fromJSON:
if let episode = Episode(map: map) {
self = episode
}
case .toJSON:
id >>> (map["tvdb_id"], StringTransform())
tmdbId >>> map["ids.tmdb"]
imdbId >>> map["ids.imdb"]
firstAirDate >>> (map["first_aired"], DateTransform())
summary >>> map["overview"]
season >>> map["season"]
show >>> map["show"]
episode >>> map["episode"]
largeBackgroundImage >>> map["images.fanart"]
title >>> map["title"]
}
}
public var mediaItemDictionary: [String: Any] {
return [MPMediaItemPropertyTitle: title,
MPMediaItemPropertyMediaType: NSNumber(value: MPMediaType.episode.rawValue),
MPMediaItemPropertyPersistentID: id,
MPMediaItemPropertyArtwork: smallBackgroundImage ?? "",
MPMediaItemPropertyBackgroundArtwork: smallBackgroundImage ?? "",
MPMediaItemPropertySummary: summary,
MPMediaItemPropertyShow: show?.mediaItemDictionary ?? [:],
MPMediaItemPropertyEpisode: episode,
MPMediaItemPropertySeason: season]
}
public init?(_ mediaItemDictionary: [String: Any]) {
guard
let rawValue = mediaItemDictionary[MPMediaItemPropertyMediaType] as? NSNumber,
let type = MPMediaType(rawValue: rawValue.uintValue) as MPMediaType?,
type == MPMediaType.episode,
let id = mediaItemDictionary[MPMediaItemPropertyPersistentID] as? String,
let title = mediaItemDictionary[MPMediaItemPropertyTitle] as? String,
let backgroundImage = mediaItemDictionary[MPMediaItemPropertyBackgroundArtwork] as? String,
let summary = mediaItemDictionary[MPMediaItemPropertySummary] as? String,
let showMediaItemDictionary = mediaItemDictionary[MPMediaItemPropertyShow] as? [String: Any],
let episode = mediaItemDictionary[MPMediaItemPropertyEpisode] as? Int,
let season = mediaItemDictionary[MPMediaItemPropertySeason] as? Int
else {
return nil
}
let largeBackgroundImage = backgroundImage.replacingOccurrences(of: backgroundImage.isAmazonUrl ? "SX300" : "w300", with: backgroundImage.isAmazonUrl ? "SX1000" : "w780")
self.init(title: title, id: id, slug: title.slugged, summary: summary, largeBackgroundImage: largeBackgroundImage, show: Show(showMediaItemDictionary), episode: episode, season: season)
}
}
// MARK: - Hashable
extension Episode: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id.hashValue)
}
}
// MARK: Equatable
public func ==(lhs: Episode, rhs: Episode) -> Bool {
return lhs.id == rhs.id
}
|
gpl-3.0
|
97b75ece73187e59c957834b89b43404
| 49.412698 | 399 | 0.651973 | 4.631988 | false | false | false | false |
JeeLiu/AutoLayoutCrossOverScrollViewDemo
|
Demo/AutoLayoutCrossOverScrollViewDemo/AutoLayoutCrossOverScrollViewDemo/HOCCStoryBoardController.swift
|
2
|
1270
|
//
// HOCCStoryBoardController.swift
// AutoLayoutCrossOverScrollViewDemo
//
// Created by Fasa Mo on 15/9/1.
// Copyright (c) 2015年 FasaMo. All rights reserved.
//
import UIKit
class HOCCStoryBoardController: UIViewController {
var didSetupConstraints = false
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var imageView: UIImageView! {
didSet {
imageView.image = UIImage(named: "hocc")
if let image = imageView.image {
let ratio = image.size.height / image.size.width
imageView.autoMatchDimension(.Height, toDimension: .Width, ofView: imageView, withMultiplier: ratio)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
// MARK: UpdateViewConstraints
extension HOCCStoryBoardController {
override func updateViewConstraints() {
if !didSetupConstraints {
// Remove ImageViewHeightConstraint
if let imageViewHeightConstraint = imageViewHeightConstraint{
imageView.removeConstraint(imageViewHeightConstraint)
}
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
|
mit
|
f9ec6aff5b8a2d52473aeda6bc7c3705
| 26.586957 | 116 | 0.641167 | 5.196721 | false | false | false | false |
jimrutherford/TPTSwipingTableViewCell
|
TPTSwipingTableViewCell/TableViewController.swift
|
1
|
1139
|
//
// TableViewController.swift
// TPTSwipingTableViewCell
//
// Created by Jim Rutherford on 2015-07-30.
// Copyright © 2015 Braxio Interactive. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
let tableData = ["The Barr Brothers", "Avvett Brothers"]
override func viewDidLoad() {
super.viewDidLoad()
//tableView.delegate = self;
//tableView.dataSource = self;
self.tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70.0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("swipeCell", forIndexPath: indexPath)
cell.textLabel!.text = tableData[indexPath.row]
return cell
}
}
|
mit
|
dc516fc0ffff06fd80360c96e968557d
| 24.288889 | 118 | 0.677504 | 5.057778 | false | false | false | false |
apple/swift-argument-parser
|
Tools/generate-manual/DSL/Exit.swift
|
1
|
703
|
//===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import ArgumentParserToolInfo
struct Exit: MDocComponent {
var section: Int
var body: MDocComponent {
Section(title: "exit status") {
if [1, 6, 8].contains(section) {
MDocMacro.ExitStandard()
}
}
}
}
|
apache-2.0
|
1a37d2dcfb86d80a94dcf636d8bd25f2
| 27.12 | 80 | 0.544808 | 4.950704 | false | false | false | false |
hrscy/TodayNews
|
News/News/Classes/Video/Controller/RelatedVideoTableViewController.swift
|
1
|
2453
|
//
// RelatedVideoTableViewController.swift
// News
//
// Created by 杨蒙 on 2018/1/21.
// Copyright © 2018年 hrscy. All rights reserved.
//
// ********************暂未使用******************
// ********************仅供参考******************
import UIKit
import RxSwift
import RxCocoa
class RelatedVideoTableViewController: UITableViewController {
/// 头部
private lazy var headerView = RelatedVideoHeaderView.loadViewFromNib()
/// 尾部
private lazy var footerView = RelatedVideoFooterView.loadViewFromNib()
/// 视频详情
var videoDetail = VideoDetail()
/// 当前视频数据
var video = NewsModel()
private lazy var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
headerView.video = video
tableView.tableHeaderView = headerView
footerView.ad = videoDetail.ad
tableView.tableFooterView = footerView
tableView.ym_registerCell(cell: RelatedVideoCell.self)
// 展开按钮
headerView.foldButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
self!.tableView.tableHeaderView = self!.headerView
self!.tableView.reloadData()
})
.disposed(by: disposeBag)
// 查看更多
footerView.moreButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
self!.tableView.rowHeight = 80
self!.tableView.reloadData()
})
.disposed(by: disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoDetail.related_video_toutiao.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return (indexPath.row >= videoDetail.related_video_section ? 0 : 80)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as RelatedVideoCell
cell.relatedVideo = videoDetail.related_video_toutiao[indexPath.row]
return cell
}
}
|
mit
|
8a866db781ee96dc5352b3ca73ab383d
| 33.085714 | 109 | 0.633697 | 5.002096 | false | false | false | false |
radubozga/Freedom
|
speech/Swift/Speech-gRPC-Streaming/Pods/DynamicButton/Sources/DynamicButtonStyle.swift
|
1
|
6610
|
/*
* DynamicButton
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* 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
extension DynamicButton {
/**
A collection of predefined buton styles.
*/
public enum Style {
/// Downwards arrow: ↓
case arrowDown
/// Leftwards arrow: ←
case arrowLeft
/// Rightwards arrow: →
case arrowRight
/// Upwards arrow: ↑
case arrowUp
/// Down caret: ⌄
case caretDown
/// Left caret: ‹
case caretLeft
/// Left caret: ›
case caretRight
/// Up caret: ⌃
case caretUp
/// Check mark: ✓
case checkMark
/// Close symbol surrounded by a circle
case circleClose
/// Plus symbol surrounded by a circle
case circlePlus
/// Close symbol: X
case close
/// Dot symbol: .
case dot
/// Downwards triangle-headed arrow to bar: ⤓
case download
/// Fast forward: ≫
case fastForward
/// Hamburger button: ≡
case hamburger
/// Horizontal line: ―
case horizontalLine
/// Horizontal more options: …
case horizontalMoreOptions
/// No style
case none
/// Pause symbol: ‖
case pause
/// Play symbol: ► \{U+25B6}
case play
/// Plus symbol: +
case plus
/// Reload symbol: ↻
case reload
/// Rewind symbol: ≪
case rewind
/// Stop symbol: ◼ \{U+2588}
case stop
/// Vertical line: |
case verticalLine
/// Vertical more options: ⋮
case verticalMoreOptions
/// Custom style with its associate buildable style
case custom(DynamicButtonBuildableStyle.Type)
/// Returns all the available styles
public static let all: [Style] = Style.buildableByStyle.map { $0 }.sorted { $0.0.value.styleName < $0.1.value.styleName }.map { $0.0 }
// MARK: - Building Button Styles
public func build(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) -> DynamicButtonBuildableStyle {
switch self {
case .custom(let buildable):
return buildable.init(center: center, size: size, offset: offset, lineWidth: lineWidth)
default:
let buildable = Style.buildableByStyle[self]!
return buildable.init(center: center, size: size, offset: offset, lineWidth: lineWidth)
}
}
public var description: String {
let buildable = Style.buildableByStyle[self]!
return buildable.styleName
}
// MARK: - Convenient Style Description
private static let buildableByStyle: [Style: DynamicButtonBuildableStyle.Type] = [
none: DynamicButtonStyleNone.self,
arrowDown: DynamicButtonStyleArrowDown.self,
arrowLeft: DynamicButtonStyleArrowLeft.self,
arrowRight: DynamicButtonStyleArrowRight.self,
arrowUp: DynamicButtonStyleArrowUp.self,
caretDown: DynamicButtonStyleCaretDown.self,
caretLeft: DynamicButtonStyleCaretLeft.self,
caretRight: DynamicButtonStyleCaretRight.self,
caretUp: DynamicButtonStyleCaretUp.self,
checkMark: DynamicButtonStyleCheckMark.self,
circleClose: DynamicButtonStyleCircleClose.self,
circlePlus: DynamicButtonStyleCirclePlus.self,
close: DynamicButtonStyleClose.self,
plus: DynamicButtonStylePlus.self,
dot: DynamicButtonStyleDot.self,
download: DynamicButtonStyleDownload.self,
reload: DynamicButtonStyleReload.self,
rewind: DynamicButtonStyleRewind.self,
fastForward: DynamicButtonStyleFastForward.self,
play: DynamicButtonStylePlay.self,
pause: DynamicButtonStylePause.self,
stop: DynamicButtonStyleStop.self,
hamburger: DynamicButtonStyleHamburger.self,
horizontalLine: DynamicButtonStyleHorizontalLine.self,
verticalLine: DynamicButtonStyleVerticalLine.self,
horizontalMoreOptions: DynamicButtonStyleHorizontalMoreOptions.self,
verticalMoreOptions: DynamicButtonStyleVerticalMoreOptions.self
]
/**
Returns the style with the given style name.
- parameter styleName: the style name defined by the `DynamicButtonBuildableStyle` protocol.
*/
public static let styleByName: [String: Style] = Style.buildableByStyle.reduce([:]) { (acc, entry) in
var acc = acc
acc[entry.1.styleName] = entry.0
return acc
}
}
}
extension DynamicButton.Style: Equatable {
public static func ==(lhs: DynamicButton.Style, rhs: DynamicButton.Style) -> Bool {
switch (lhs, rhs) {
case (.none, .none), (.arrowDown, .arrowDown), (.arrowLeft, .arrowLeft), (.arrowRight, .arrowRight), (.arrowUp, .arrowUp), (.caretDown, .caretDown), (.caretLeft, .caretLeft), (.caretRight, .caretRight), (.caretUp, .caretUp), (.checkMark, .checkMark), (.circleClose, .circleClose), (.circlePlus, .circlePlus), (.close, .close), (.plus, .plus), (.dot, .dot), (.download, .download), (.reload, .reload), (.rewind, .rewind), (.fastForward, .fastForward), (.play, .play), (.pause, .pause), (.stop, .stop), (.hamburger, .hamburger), (.horizontalLine, .horizontalLine), (.verticalLine, .verticalLine), (.horizontalMoreOptions, .horizontalMoreOptions), (.verticalMoreOptions, .verticalMoreOptions):
return true
case (.custom(let b1), .custom(let b2)):
return b1.styleName == b2.styleName
default:
return false
}
}
}
extension DynamicButton.Style: Hashable {
public var hashValue: Int {
switch self {
case .none:
return 0
case .custom(let buildable):
return buildable.styleName.hashValue
default:
return 1
}
}
}
|
apache-2.0
|
d7fbcdff003f438cd49415a2bf7a6521
| 34.706522 | 694 | 0.689498 | 4.433198 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Home/Buildings/Buildings/Cells/BuildingSectionHeader.swift
|
1
|
992
|
//
// BuildingSectionHeader.swift
// PennMobile
//
// Created by dominic on 7/14/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
import UIKit
class BuildingSectionHeader: UITableViewHeaderFooterView {
static let headerHeight: CGFloat = 25
var label: UILabel = {
let label = UILabel()
label.font = UIFont.primaryTitleFont.withSize(18.0)
label.textColor = .labelPrimary
label.textAlignment = .left
label.text = ""
return label
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .white
addSubview(label)
_ = label.anchor(nil, left: leftAnchor, bottom: bottomAnchor, right: nil, topConstant: 0, leftConstant: 14, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
d414fb55189c7cbb610a6de3db32539d
| 26.527778 | 189 | 0.664985 | 4.484163 | false | false | false | false |
ingresse/ios-sdk
|
IngresseSDK/Services/LiveEventService.swift
|
1
|
753
|
//
// Copyright © 2020 Ingresse. All rights reserved.
//
public class LiveEventService: BaseService {
public func getEventLiveURL(request: Request.Event.LiveEvent, onSuccess: @escaping (_ url: URLRequest) -> Void, onError: @escaping ErrorHandler) {
var builder = URLBuilder(client: client)
.setHost(.ingresseLive)
.addEncodableParameter(request)
if client.environment != .prod {
let env = client.environment.rawValue.replacingOccurrences(of: "-", with: "")
builder = builder.addParameter(key: "env", value: env)
}
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
onSuccess(request)
}
}
|
mit
|
88e31b2cdd3d324c27a731fad1944af8
| 31.695652 | 150 | 0.631649 | 4.53012 | false | false | false | false |
Bizzi-Body/ParseTutorialPart8---CompleteSolution
|
ParseTutorial/DetailViewController.swift
|
1
|
4692
|
//
// DetailViewController.swift
// ParseTutorial
//
// Created by Ian Bradbury on 06/02/2015.
// Copyright (c) 2015 bizzi-body. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
// User selected object
var currentObject : PFObject?
// Object to update
var updateObject : PFObject?
// Image Picker object
var imagePicker = UIImagePickerController()
var imageDidChange = false
// Some text fields
@IBOutlet weak var nameEnglish: UITextField!
@IBOutlet weak var nameLocal: UITextField!
@IBOutlet weak var capital: UITextField!
@IBOutlet weak var currencyCode: UITextField!
@IBOutlet weak var flag: PFImageView!
// The save button
@IBAction func saveButton(sender: AnyObject) {
// Use the sent country object or create a new country PFObject
if let updateObjectTest = currentObject as PFObject? {
updateObject = currentObject! as PFObject
} else {
updateObject = PFObject(className:"Countries")
}
// Update the object
if let updateObject = updateObject {
updateObject["nameEnglish"] = nameEnglish.text
updateObject["nameLocal"] = nameLocal.text
updateObject["capital"] = capital.text
updateObject["currencyCode"] = currencyCode.text
// Create a string of text that is used by search capabilites
var searchText = (capital.text + " " + nameEnglish.text + " " + nameLocal.text + " " + currencyCode.text).lowercaseString
updateObject["searchText"] = searchText
// Upload any flag image
if imageDidChange == true {
let imageData = UIImagePNGRepresentation(flag.image)
let fileName = nameEnglish.text + ".png"
let imageFile = PFFile(name:fileName, data:imageData)
updateObject["flag"] = imageFile
}
// Update the record ACL such that the new record is only visible to the current user
updateObject.ACL = PFACL(user: PFUser.currentUser()!)
// Save the data back to the server in a background task
updateObject.save()
}
// Return to table view
self.navigationController?.popViewControllerAnimated(true)
}
// Present image picker
// Will prompt user to allow permission to device photo library
@IBAction func uploadFlagImage(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
}
// Process selected image - add image to the parse object model
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Update the image within the app interface
flag.image = pickedImage
flag.contentMode = .ScaleAspectFit
// Update the image did change flag so that we pick this up when the country is ssaved back to Parse
imageDidChange = true
}
// Dismiss the image picker
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Configure delegate property for the form fields
nameEnglish.delegate = self
nameLocal.delegate = self
capital.delegate = self
currencyCode.delegate = self
// Unwrap the current object object
if let object = currentObject {
if let value = object["nameEnglish"] as? String {
nameEnglish.text = value
}
if let value = object["nameLocal"] as? String {
nameLocal.text = value
}
if let value = object["capital"] as? String {
capital.text = value
}
if let value = object["currencyCode"] as? String {
currencyCode.text = value
}
// Display standard question image
var initialThumbnail = UIImage(named: "question")
flag.image = initialThumbnail
// Replace question image if an image exists on the parse platform
if let thumbnail = object["flag"] as? PFFile {
flag.file = thumbnail
flag.loadInBackground()
}
}
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
mit
|
fa1cd684370e6a4a9abb6e3875f27f41
| 30.918367 | 132 | 0.683078 | 5.111111 | false | false | false | false |
makingspace/NetworkingServiceKit
|
Example/Tests/TwitterAuthenticationServiceTests.swift
|
1
|
5153
|
//
// TwitterAuthenticationServiceTests.swift
// NetworkingServiceKit
//
// Created by Phillipe Casorla Sagot (@darkzlave) on 4/5/17.
// Copyright © 2017 Makespace Inc. All rights reserved.
//
import Quick
import Nimble
import NetworkingServiceKit
class TwitterAuthenticationServiceTests: QuickSpec, ServiceLocatorDelegate {
var delegateGot401 = false
override func spec() {
let authStub = ServiceStub(execute: ServiceStubRequest(path: "/oauth2/token"),
with: .success(code: 200, response: ["token_type" : "access", "access_token" : "KWALI"]),
when: .unauthenticated,
react:.immediate)
let logoutStub = ServiceStub(execute: ServiceStubRequest(path: "/oauth2/invalidate_token"),
with: .success(code: 200, response: [:]),
when: .unauthenticated,
react:.immediate)
let logoutStubUnauthenticated = ServiceStub(execute: ServiceStubRequest(path: "/oauth2/invalidate_token"),
with: .failure(code:401, response:[:]),
when: .unauthenticated,
react:.immediate)
let logoutStubAuthenticated = ServiceStub(execute: ServiceStubRequest(path: "/oauth2/invalidate_token"),
with: .failure(code:401, response:[:]),
when: .authenticated(tokenInfo: ["token_type" : "access", "access_token" : "KWALI"]),
react:.immediate)
beforeEach {
ServiceLocator.defaultNetworkClientType = StubNetworkManager.self
self.delegateGot401 = false
UserDefaults.clearServiceLocatorUserDefaults()
APITokenManager.clearAuthentication()
ServiceLocator.reset()
ServiceLocator.set(services: [TwitterAuthenticationService.self],
api: TwitterAPIConfigurationType.self,
auth: TwitterApp.self,
token: TwitterAPIToken.self)
}
describe("when a user is authenticating through our Authenticate service") {
context("and the credentials are correct") {
it("should be authenticated") {
let authenticationService = ServiceLocator.service(forType: TwitterAuthenticationService.self, stubs: [authStub])
authenticationService?.authenticateTwitterClient(completion: { authenticated in
expect(authenticated).to(beTrue())
})
}
}
}
describe("when the current user is already authenticated") {
context("and is trying to logout") {
it("should clear token data") {
let authenticationService = ServiceLocator.service(forType: TwitterAuthenticationService.self, stubs: [logoutStub])
authenticationService?.logoutTwitterClient(completion: { loggedOut in
expect(loggedOut).to(beTrue())
})
}
}
}
describe("when the current user is NOT authenticated") {
context("and is trying to logout") {
it("should not return succesfully") {
let authenticationService = ServiceLocator.service(forType: TwitterAuthenticationService.self, stubs: [logoutStubUnauthenticated])
authenticationService?.logoutTwitterClient(completion: { loggedOut in
expect(loggedOut).to(beFalse())
})
}
}
}
describe("when we are authenticated but the token has expired") {
context("and is trying to logout") {
it("should report to the delegate there is a token expired") {
//set ourselves as delegate
ServiceLocator.setDelegate(delegate: self)
let authenticationService = ServiceLocator.service(forType: TwitterAuthenticationService.self, stubs: [logoutStubAuthenticated])
authenticationService?.logoutTwitterClient(completion: { loggedOut in
expect(loggedOut).to(beFalse())
expect(self.delegateGot401).to(beTrue())
})
}
}
}
}
// MARK: ServiceLocatorDelegate
func authenticationTokenDidExpire(forService service: Service) {
self.delegateGot401 = true
}
func shouldInterceptRequest(with request: URLRequest) -> Bool {
return false
}
func processIntercept(for request: NSMutableURLRequest) -> URLRequest? {
return nil
}
}
|
mit
|
04b36876eae9e0152ca75ef3fd5e137b
| 45.414414 | 150 | 0.538626 | 6.068316 | false | false | false | false |
Jnosh/swift
|
test/decl/protocol/conforms/placement.swift
|
2
|
10495
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend %S/Inputs/placement_module_A.swift -emit-module -parse-as-library -o %t
// RUN: %target-swift-frontend -I %t %S/Inputs/placement_module_B.swift -emit-module -parse-as-library -o %t
// RUN: %target-swift-frontend -typecheck -primary-file %s %S/Inputs/placement_2.swift -I %t -verify
// Tests for the placement of conformances as well as conflicts
// between conformances that come from different sources.
import placement_module_A
import placement_module_B
protocol P1 { }
protocol P2a : P1 { }
protocol P3a : P2a { }
protocol P2b : P1 { }
protocol P3b : P2b { }
protocol P4 : P3a, P3b { }
protocol AnyObjectRefinement : AnyObject { }
// ===========================================================================
// Tests within a single source file
// ===========================================================================
// ---------------------------------------------------------------------------
// Multiple explicit conformances to the same protocol
// ---------------------------------------------------------------------------
struct Explicit1 : P1 { } // expected-note{{'Explicit1' declares conformance to protocol 'P1' here}}
extension Explicit1 : P1 { } // expected-error{{redundant conformance of 'Explicit1' to protocol 'P1'}}
struct Explicit2 { }
extension Explicit2 : P1 { } // expected-note 2{{'Explicit2' declares conformance to protocol 'P1' here}}
extension Explicit2 : P1 { } // expected-error{{redundant conformance of 'Explicit2' to protocol 'P1'}}
extension Explicit2 : P1 { } // expected-error{{redundant conformance of 'Explicit2' to protocol 'P1'}}
// ---------------------------------------------------------------------------
// Multiple implicit conformances, with no ambiguities
// ---------------------------------------------------------------------------
struct MultipleImplicit1 : P2a { }
extension MultipleImplicit1 : P3a { }
struct MultipleImplicit2 : P4 { }
struct MultipleImplicit3 : P4 { }
extension MultipleImplicit3 : P1 { }
// ---------------------------------------------------------------------------
// Multiple implicit conformances, ambiguity resolved because they
// land in the same context.
// ---------------------------------------------------------------------------
struct MultipleImplicit4 : P2a, P2b { }
struct MultipleImplicit5 { }
extension MultipleImplicit5 : P2a, P2b { }
struct MultipleImplicit6 : P4 { }
extension MultipleImplicit6 : P3a { }
struct MultipleImplicit7 : P2a { }
extension MultipleImplicit7 : P2b { }
// ---------------------------------------------------------------------------
// Multiple implicit conformances, ambiguity resolved via explicit conformance
// ---------------------------------------------------------------------------
struct ExplicitMultipleImplicit1 : P2a { }
extension ExplicitMultipleImplicit1 : P2b { }
extension ExplicitMultipleImplicit1 : P1 { } // resolves ambiguity
// ---------------------------------------------------------------------------
// Implicit conformances superseded by inherited conformances
// ---------------------------------------------------------------------------
class ImplicitSuper1 : P3a { }
class ImplicitSub1 : ImplicitSuper1 { }
extension ImplicitSub1 : P4 { } // okay, introduces new conformance to P4; the rest are superseded
// ---------------------------------------------------------------------------
// Synthesized conformances superseded by implicit conformances
// ---------------------------------------------------------------------------
enum SuitA { case Spades, Hearts, Clubs, Diamonds }
func <(lhs: SuitA, rhs: SuitA) -> Bool { return false }
extension SuitA : Comparable {} // okay, implied conformance to Equatable here is preferred.
enum SuitB: Equatable { case Spades, Hearts, Clubs, Diamonds }
func <(lhs: SuitB, rhs: SuitB) -> Bool { return false }
extension SuitB : Comparable {} // okay, explicitly declared earlier.
enum SuitC { case Spades, Hearts, Clubs, Diamonds }
func <(lhs: SuitC, rhs: SuitC) -> Bool { return false }
extension SuitC : Equatable, Comparable {} // okay, explicitly declared here.
// ---------------------------------------------------------------------------
// Explicit conformances conflicting with inherited conformances
// ---------------------------------------------------------------------------
class ExplicitSuper1 : P3a { }
class ExplicitSub1 : ImplicitSuper1 { } // expected-note{{'ExplicitSub1' inherits conformance to protocol 'P1' from superclass here}}
extension ExplicitSub1 : P1 { } // expected-error{{redundant conformance of 'ExplicitSub1' to protocol 'P1'}}
// ---------------------------------------------------------------------------
// Suppression of synthesized conformances
// ---------------------------------------------------------------------------
class SynthesizedClass1 : AnyObject { } // expected-warning{{conformance of class 'SynthesizedClass1' to 'AnyObject' is redundant}}
class SynthesizedClass2 { }
extension SynthesizedClass2 : AnyObject { } // expected-error{{inheritance from non-protocol type 'AnyObject'}}
class SynthesizedClass3 : AnyObjectRefinement { }
class SynthesizedClass4 { }
extension SynthesizedClass4 : AnyObjectRefinement { }
class SynthesizedSubClass1 : SynthesizedClass1, AnyObject { } // expected-warning{{conformance of class 'SynthesizedSubClass1' to 'AnyObject' is redundant}}
class SynthesizedSubClass2 : SynthesizedClass2 { }
extension SynthesizedSubClass2 : AnyObject { } // expected-error{{inheritance from non-protocol type 'AnyObject'}}
class SynthesizedSubClass3 : SynthesizedClass1, AnyObjectRefinement { }
class SynthesizedSubClass4 : SynthesizedClass2 { }
extension SynthesizedSubClass4 : AnyObjectRefinement { }
enum SynthesizedEnum1 : Int, RawRepresentable { case none = 0 }
enum SynthesizedEnum2 : Int { case none = 0 }
extension SynthesizedEnum2 : RawRepresentable { }
// ===========================================================================
// Tests across different source files
// ===========================================================================
// ---------------------------------------------------------------------------
// Multiple explicit conformances to the same protocol
// ---------------------------------------------------------------------------
struct MFExplicit1 : P1 { }
extension MFExplicit2 : P1 { } // expected-error{{redundant conformance of 'MFExplicit2' to protocol 'P1'}}
// ---------------------------------------------------------------------------
// Multiple implicit conformances, with no ambiguities
// ---------------------------------------------------------------------------
extension MFMultipleImplicit1 : P3a { }
struct MFMultipleImplicit2 : P4 { }
extension MFMultipleImplicit3 : P1 { }
extension MFMultipleImplicit4 : P3a { }
extension MFMultipleImplicit5 : P2b { }
// ---------------------------------------------------------------------------
// Explicit conformances conflicting with inherited conformances
// ---------------------------------------------------------------------------
class MFExplicitSuper1 : P3a { }
extension MFExplicitSub1 : P1 { } // expected-error{{redundant conformance of 'MFExplicitSub1' to protocol 'P1'}}
// ---------------------------------------------------------------------------
// Suppression of synthesized conformances
// ---------------------------------------------------------------------------
class MFSynthesizedClass1 { }
extension MFSynthesizedClass2 : AnyObject { } // expected-error{{inheritance from non-protocol type 'AnyObject'}}
class MFSynthesizedClass4 { }
extension MFSynthesizedClass4 : AnyObjectRefinement { }
extension MFSynthesizedSubClass2 : AnyObject { } // expected-error{{inheritance from non-protocol type 'AnyObject'}}
extension MFSynthesizedSubClass3 : AnyObjectRefinement { }
class MFSynthesizedSubClass4 : MFSynthesizedClass2 { }
extension MFSynthesizedEnum1 : RawRepresentable { }
enum MFSynthesizedEnum2 : Int { case none = 0 }
// ===========================================================================
// Tests with conformances in imported modules
// ===========================================================================
extension MMExplicit1 : MMP1 { } // expected-warning{{conformance of 'MMExplicit1' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}}
extension MMExplicit1 : MMP2a { } // expected-warning{{MMExplicit1' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A}}
extension MMExplicit1 : MMP3a { } // expected-warning{{conformance of 'MMExplicit1' to protocol 'MMP3a' was already stated in the type's module 'placement_module_A'}}
extension MMExplicit1 : MMP3b { } // okay
extension MMSuper1 : MMP1 { } // expected-warning{{conformance of 'MMSuper1' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}}
extension MMSuper1 : MMP2a { } // expected-warning{{conformance of 'MMSuper1' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}}
extension MMSuper1 : MMP3b { } // okay
extension MMSub1 : AnyObject { } // expected-error{{inheritance from non-protocol type 'AnyObject'}}
extension MMSub2 : MMP1 { } // expected-warning{{conformance of 'MMSub2' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}}
extension MMSub2 : MMP2a { } // expected-warning{{conformance of 'MMSub2' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}}
extension MMSub2 : MMP3b { } // okay
extension MMSub2 : MMAnyObjectRefinement { } // okay
extension MMSub3 : MMP1 { } // expected-warning{{conformance of 'MMSub3' to protocol 'MMP1' was already stated in the type's module 'placement_module_A'}}
extension MMSub3 : MMP2a { } // expected-warning{{conformance of 'MMSub3' to protocol 'MMP2a' was already stated in the type's module 'placement_module_A'}}
extension MMSub3 : MMP3b { } // okay
extension MMSub3 : AnyObject { } // expected-error{{inheritance from non-protocol type 'AnyObject'}}
extension MMSub4 : MMP1 { } // expected-warning{{conformance of 'MMSub4' to protocol 'MMP1' was already stated in the type's module 'placement_module_B'}}
extension MMSub4 : MMP2a { } // expected-warning{{conformance of 'MMSub4' to protocol 'MMP2a' was already stated in the type's module 'placement_module_B'}}
extension MMSub4 : MMP3b { } // okay
extension MMSub4 : AnyObjectRefinement { } // okay
|
apache-2.0
|
33c6eee7e67760561a0c8a0fc0b438d1
| 47.142202 | 166 | 0.583421 | 4.95983 | false | false | false | false |
tensorflow/examples
|
lite/examples/style_transfer/ios/StyleTransfer/StylePickerViewController.swift
|
1
|
3734
|
// Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
protocol StylePickerViewControllerDelegate {
func picker(_: StylePickerViewController, didSelectStyle image: UIImage)
}
class StylePickerViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var delegate: StylePickerViewControllerDelegate?
class func fromStoryboard() -> StylePickerViewController {
return UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "StylePickerViewController")
as! StylePickerViewController
}
private let dataSource = StylePickerDataSource()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = dataSource
collectionView.delegate = self
}
override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
if let image = dataSource.imageForStyle(at: indexPath.item) {
collectionView.deselectItem(at: indexPath, animated: true)
delegate?.picker(self, didSelectStyle: image)
dismiss(animated: true, completion: nil)
}
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let layout = collectionViewLayout as? UICollectionViewFlowLayout else { return .zero }
let smallestDimension = collectionView.bounds.width < collectionView.bounds.height ?
collectionView.bounds.width : collectionView.bounds.height
let extraPadding: CGFloat = 3 // magic number
let itemDimension =
smallestDimension / 2 - collectionView.contentInset.left - collectionView.contentInset.right
- layout.sectionInset.left - layout.sectionInset.right - layout.minimumInteritemSpacing
- extraPadding
return CGSize(width: itemDimension, height: itemDimension)
}
}
class StylePickerDataSource: NSObject, UICollectionViewDataSource {
static func defaultStyle() -> UIImage {
return UIImage(named: "style24")! // use great wave as default
}
lazy private var images: [UIImage] = {
var index = 0
var images: [UIImage] = []
while let image = UIImage(named: "style\(index)") {
images.append(image)
index += 1
}
return images
}()
func imageForStyle(at index: Int) -> UIImage? {
return images[index]
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StylePickerCell",
for: indexPath) as! StylePickerCollectionViewCell
let image = imageForStyle(at: indexPath.item)
cell.styleImageView.image = image
return cell
}
}
class StylePickerCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var styleImageView: UIImageView!
}
|
apache-2.0
|
7336748316f6f497b16c2247d0ef340c
| 34.226415 | 100 | 0.714783 | 5.288952 | false | false | false | false |
michaello/Aloha
|
AlohaGIF/VideoPreviewViewController.swift
|
1
|
12629
|
//
// VideoPreviewViewController.swift
// AlohaGIF
//
// Created by Michal Pyrka on 17/04/2017.
// Copyright © 2017 Michal Pyrka. All rights reserved.
//
import UIKit
import AVFoundation
final class VideoPreviewViewController: UIViewController {
private enum Constants {
static let loopCountKeyPath = #keyPath(AVPlayerLooper.loopCount)
static let isReadyForDisplayKeyPath = #keyPath(AVPlayerLayer.isReadyForDisplay)
static let increasedTouchInsets = UIEdgeInsets(top: -20.0, left: -20.0, bottom: -10.0, right: -20.0)
}
@IBOutlet private weak var arrowButton: UIButton!
@IBOutlet private weak var movieToolbarBackgroundContainerView: UIVisualEffectView!
@IBOutlet private weak var movieToolbarContainerView: UIView!
@IBOutlet private weak var playerView: UIView!
var selectedVideo: AVAsset!
var speechArray = [SpeechModel]()
fileprivate lazy var videoToolbarCoordinator: VideoToolbarCoordinator = VideoToolbarCoordinator(selectedVideo: self.selectedVideo)
private var dynamicSubtitlesComposer: DynamicSubtitlesComposer?
private let player = AVQueuePlayer()
private lazy var playerLayer = AVPlayerLayer(player: self.player)
private lazy var playerItem = AVPlayerItem(asset: self.selectedVideo)
private lazy var playerLooper = AVPlayerLooper(player: self.player, templateItem: self.playerItem, timeRange: self.loopingDurationTimeRange())
private var loopContext = 0
private var isReadyContext = 0
var dynamicSubtitlesStyle: DynamicSubtitlesStyle = .default
fileprivate var dynamicSubtitlesView: OverlayView?
private var subtitlesInitialPointCenter: CGPoint?
private var shouldShowOverlayText = true
private var wasAlreadyPlayed = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if wasAlreadyPlayed {
player.isMuted = false
player.play()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
player.pause()
}
override func viewDidLoad() {
super.viewDidLoad()
addObservers()
setupVideoToolbarCoordinator()
setupButtons()
setupPlayer()
guard shouldShowOverlayText else { return }
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &loopContext {
guard let newValue = change?[.newKey] as? Int else { return super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) }
Logger.verbose("Replayed movie \(selectedVideo.description). Count: \(newValue)")
presentDynamicSubtitlesOverlay(dynamicSubtitlesStyle, shouldPresentSubtitlesFromBeginning: true)
} else if context == &isReadyContext {
playerLayer.removeObserver(self, forKeyPath: Constants.isReadyForDisplayKeyPath)
prepareForSubtitlesPresentation()
} else {
return super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let navigationController = segue.destination as? UINavigationController, let videoToolbarViewController = navigationController.topViewController as? VideoToolbarViewController else { return }
videoToolbarCoordinator.videoToolbarViewController = videoToolbarViewController
}
func addDynamicSubtitlesViewAndApplySubtitles() {
let subtitlesView = OverlayView(frame: view.frame)
subtitlesView.videoToolbarView = movieToolbarContainerView
subtitlesView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(VideoPreviewViewController.dynamicSubtitlesViewDidMove)))
subtitlesInitialPointCenter = subtitlesView.center
view.addSubview(subtitlesView)
dynamicSubtitlesView = subtitlesView
dynamicSubtitlesComposer = DynamicSubtitlesComposer(dynamicSubtitlesStyle: dynamicSubtitlesStyle, dynamicSubtitlesContext: DynamicSubtitlesContext.view(subtitlesView))
dynamicSubtitlesComposer?.applyDynamicSubtitles(speechArray: speechArray, size: subtitlesView.bounds.size)
}
@IBAction func exportAction(_ sender: UIButton) {
ALLoadingView.show()
exportVideoToDynamicSubtitlesVideo()
}
@IBAction func debugAction(_ sender: UIButton) {
player.remove(playerItem)
playerLooper.disableLooping()
dismiss(animated: true)
}
@IBAction func closeButtonAction(_ sender: UIButton) {
player.remove(playerItem)
playerLooper.disableLooping()
dynamicSubtitlesView?.isHidden = true
dismiss(animated: true)
}
@objc private func muteSound() {
player.isMuted = true
}
@objc private func unmuteSound() {
player.isMuted = false
}
@objc private func dynamicSubtitlesViewDidMove(sender: UIPanGestureRecognizer) {
guard let subtitlesInitialPointCenter = subtitlesInitialPointCenter, let dynamicSubtitlesView = dynamicSubtitlesView else { return }
switch sender.state {
case .began, .changed:
SharedVariables.xOffset = -(-subtitlesInitialPointCenter.x + dynamicSubtitlesView.center.x) * SharedVariables.videoScale
SharedVariables.yOffset = -(-subtitlesInitialPointCenter.y + dynamicSubtitlesView.center.y) * SharedVariables.videoScale
let center = dynamicSubtitlesView.center
let translation = sender.translation(in: dynamicSubtitlesView)
dynamicSubtitlesView.center = CGPoint(x: center.x + translation.x, y: center.y + translation.y)
sender.setTranslation(.zero, in: dynamicSubtitlesView)
default: ()
}
}
@objc private func pausePreviewWhenInBackground() {
player.pause()
}
@objc private func resumePreviewWhenInForeground() {
playerLayer = AVPlayerLayer(player: player)
player.play()
}
//TODO: For debug purposes only to check whether dynamic subtitles on video have correct position like in preview
fileprivate func presentVideoPreviewViewController(with asset: AVAsset, speechArray: [SpeechModel]? = nil) {
let videoPreviewViewController = UIStoryboard.viewController(VideoPreviewViewController.self)
videoPreviewViewController.shouldShowOverlayText = false
videoPreviewViewController.selectedVideo = asset
if let speechArray = speechArray {
videoPreviewViewController.speechArray = speechArray
}
present(videoPreviewViewController, animated: true)
}
fileprivate func presentDynamicSubtitlesOverlay(_ dynamicSubtitlesStyle: DynamicSubtitlesStyle, shouldPresentSubtitlesFromBeginning: Bool = false) {
guard let dynamicSubtitlesView = dynamicSubtitlesView, UIDevice.isNotSimulator else { return }
self.dynamicSubtitlesStyle = dynamicSubtitlesStyle
dynamicSubtitlesView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
let startTime = shouldPresentSubtitlesFromBeginning ? 0.0 : currentTimeOfPreviewMovie()
dynamicSubtitlesComposer = DynamicSubtitlesComposer(dynamicSubtitlesStyle: dynamicSubtitlesStyle, dynamicSubtitlesContext: DynamicSubtitlesContext.view(dynamicSubtitlesView))
dynamicSubtitlesComposer?.applyDynamicSubtitles(speechArray: speechArray, size: dynamicSubtitlesView.bounds.size, startTime: startTime)
}
private func prepareForSubtitlesPresentation() {
setupVideoScale()
addDynamicSubtitlesViewAndApplySubtitles()
wasAlreadyPlayed = true
}
private func setupButtons() {
arrowButton.addTarget(videoToolbarCoordinator, action: #selector(VideoToolbarCoordinator.arrowButtonAction(_:)), for: .touchUpInside)
view.subviews.forEach { ($0 as? UIButton)?.touchAreaEdgeInsets = Constants.increasedTouchInsets }
}
private func setupPlayer() {
playerLayer.frame = CGRect(origin: .zero, size: playerView.frame.size)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerView.layer.addSublayer(playerLayer)
player.play()
playerLooper.addObserver(self, forKeyPath: Constants.loopCountKeyPath, options: [.new, .old], context: &loopContext)
playerLayer.addObserver(self, forKeyPath: Constants.isReadyForDisplayKeyPath, options: [.new, .old], context: &isReadyContext)
}
private func setupVideoToolbarCoordinator() {
videoToolbarCoordinator.delegate = self
videoToolbarCoordinator.passViewsToAnimate(arrowButton: arrowButton, movieToolbarBackgroundContainerView: movieToolbarBackgroundContainerView, movieToolbarContainerView: movieToolbarContainerView)
}
//TODO: It makes analysis once again, and we already know about speech, so later is should just apply subtitles into AVAsset.
private func exportVideoToDynamicSubtitlesVideo() {
let speechController = SpeechController()
let dynamicSubtitlesVideo = DynamicSubtitlesVideo(video: selectedVideo, speechArray: speechArray, dynamicSubtitlesStyle: videoToolbarCoordinator.dynamicSubtitlesStyle)
speechController.createVideoWithDynamicSubtitles(from: dynamicSubtitlesVideo, completion: { url in
DispatchQueue.main.async {
self.prepareForVideoPreviewPresentation()
self.presentVideoPreviewViewController(with: AVURLAsset(url: url))
}
})
}
private func loopingDurationTimeRange() -> CMTimeRange {
let oneHundrethOfSecond = CMTime(value: 1, timescale: 100) //subtract 1/100 of second to avoid flickering of AVPlayerLooper
return CMTimeRange(start: kCMTimeZero, duration: selectedVideo.duration - oneHundrethOfSecond)
}
private func setupVideoScale() {
guard let videoTrack = selectedVideo.tracks(withMediaType: AVMediaTypeVideo).first else { return }
let videoSize = videoTrack.naturalSize
if videoTrack.videoAssetOrientation.isPortrait {
SharedVariables.videoScale = videoSize.width / playerLayer.videoRect.height
} else {
SharedVariables.videoScale = videoSize.height / playerLayer.videoRect.height
}
}
private func prepareForVideoPreviewPresentation() {
player.remove(playerItem)
playerLooper.disableLooping()
ALLoadingView.manager.hideLoadingView()
}
private func currentTimeOfPreviewMovie() -> Double {
return playerLooper.loopingPlayerItems
.map { $0.currentTime().seconds }
.filter { $0 > 0.0 }
.sorted()
.first ?? 0.0
}
private func addObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(VideoPreviewViewController.muteSound), name: .muteNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(VideoPreviewViewController.pausePreviewWhenInBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(VideoPreviewViewController.resumePreviewWhenInForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(VideoPreviewViewController.unmuteSound), name: .unmuteNotification, object: nil)
}
deinit {
playerLooper.removeObserver(self, forKeyPath: Constants.loopCountKeyPath)
}
}
extension VideoPreviewViewController: VideoToolbarCoordinatorDelegate {
func dynamicSubtitlesStyleDidChange(_ dynamicSubtitlesStyle: DynamicSubtitlesStyle, modification: DynamicSubtitlesModification) {
if case .effect = modification {
revertToInitialDynamicSubtitlesViewPosition()
}
presentDynamicSubtitlesOverlay(dynamicSubtitlesStyle)
}
func dynamicSubtitlesVideoForRendering() -> DynamicSubtitlesVideo {
return DynamicSubtitlesVideo(video: selectedVideo, speechArray: speechArray, dynamicSubtitlesStyle: videoToolbarCoordinator.dynamicSubtitlesStyle)
}
private func revertToInitialDynamicSubtitlesViewPosition() {
dynamicSubtitlesView?.frame = view.frame
SharedVariables.xOffset = 0.0
SharedVariables.yOffset = 0.0
}
}
|
mit
|
9790ab2b9ceb4790027a54fd1dc4557c
| 47.383142 | 205 | 0.726322 | 5.321534 | false | false | false | false |
zhiquan911/chance_btc_wallet
|
chance_btc_wallet/chance_btc_wallet/extension/UITableView+extension.swift
|
1
|
2047
|
//
// UITableView+extension.swift
// Chance_wallet
//
// Created by Chance on 15/12/10.
// Copyright © 2015年 Chance. All rights reserved.
//
import Foundation
extension UITableView {
/// 隐藏多余的空白行
func extraCellLineHidden() {
let view = UIView()
view.backgroundColor = UIColor.clear
self.tableFooterView = view
}
/**
没有数据时显示提示
*/
func tableViewDisplayWitMsg(_ message: String, rowCount: Int) {
if rowCount == 0 {
// Display a message when the table is empty
// 没有数据的时候,UILabel的显示样式
let messageLabel = UILabel()
messageLabel.text = message
messageLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
messageLabel.textColor = UIColor.lightGray
messageLabel.textAlignment = NSTextAlignment.center
messageLabel.sizeToFit()
self.backgroundView = messageLabel
} else {
self.backgroundView = nil
}
}
/**
滚动到底部
- parameter animated:
*/
func scrollToBottom(_ section: Int = 0, animated: Bool = false) {
if self.numberOfRows(inSection: section) > 0 {
let indexPath: IndexPath = IndexPath(
row: self.numberOfRows(inSection: section) - 1,
section: section)
self.scrollToRow(
at: indexPath,
at: UITableViewScrollPosition.bottom,
animated: animated)
}
}
/**
滚动到底部
- parameter animated:
*/
func scrollToTop(_ section: Int = 0, animated: Bool = false) {
let indexPath: IndexPath = IndexPath(
row: 0,
section: section)
self.scrollToRow(
at: indexPath,
at: UITableViewScrollPosition.bottom,
animated: animated)
}
}
|
mit
|
9ff435717e9a752c1498696ec8b3f229
| 24.842105 | 88 | 0.544807 | 5.127937 | false | false | false | false |
maxbritto/cours-ios11-swift4
|
swift_4_cours_complet.playground/Pages/Maths.xcplaygroundpage/Contents.swift
|
1
|
375
|
//: [< Sommaire](Sommaire)
/*:
# Fonctions Mathématiques
---
### Maxime Britto - Swift 4
*/
let score1 = 10
let score2 = 100
let score3 = 200
let score4 = 5
let bestScore = max(score1, score2, score3, score4)
let worstScore = min(score1, score2, score3, score4)
import Foundation
let racine = sqrt(9.0)
let bitParOctets = pow(2, 8)
/*:
[< Sommaire](Sommaire)
*/
|
apache-2.0
|
fd4f620c3e18aaba8f3677f53cef7dd4
| 14.583333 | 52 | 0.660428 | 2.615385 | false | false | false | false |
qmathe/SwiftBits
|
Search/BinarySearch.swift
|
1
|
1811
|
//
// BinarySearch.swift
// SwiftBits
//
// Created by Quentin Mathé on 15/07/2014.
// Copyright (c) 2014 Quentin Mathé. All rights reserved.
//
import Foundation
func midpoint<T: Integer>(min: T, max: T) -> T
{
assert(min <= max);
return min + (max - min) / 2
}
/**
* C.IndexType must be declared as Integer to support arithmetic computations
* such as midpoint() or assert(min <= max). As a counter example,
* BidirectionalIndex supports navigation but not computation.
*/
func binarySearchInRange<C: Swift.Collection, T: Comparable where T == C.GeneratorType.Element, C.IndexType: Integer>(sequence: C, value: T, min: C.IndexType, max: C.IndexType) -> T?
{
assert(min <= max);
if min == max
{
return value == sequence[min] ? value : nil
}
let middle = midpoint(min, max);
if value < sequence[middle]
{
return binarySearchInRange(sequence, value, min, middle - 1)
}
else if value > sequence[middle]
{
return binarySearchInRange(sequence, value, middle + 1, max)
}
else
{
assert(value == sequence[middle])
return value
}
}
func binarySearch<T: Comparable>(sequence: [T], value: T) -> T?
{
return binarySearchInRange(sequence, value, 0, sequence.count - 1)
}
func binarySearchInRangeIterative<C: Swift.Collection, T: Comparable where T == C.GeneratorType.Element, C.IndexType: Integer>(sequence: C, value: T, minIndex: C.IndexType, maxIndex: C.IndexType) -> T?
{
var min = minIndex;
var max = maxIndex;
assert(min <= max);
while min <= max
{
if min == max
{
return value == sequence[min] ? value : nil
}
let middle = midpoint(min, max)
if value < sequence[middle]
{
max = middle - 1
}
else if value > sequence[middle]
{
min = middle + 1
}
else
{
assert(value == sequence[middle])
return value
}
}
return nil
}
|
mit
|
4d2e86cd179c480184ef6285aea30165
| 20.282353 | 201 | 0.665561 | 3.157068 | false | false | false | false |
ricealexanderb/forager
|
PatchListViewController.swift
|
1
|
5183
|
//
// PatchListViewController.swift
// Foragr
//
// Created by Alex on 8/12/14.
// Copyright (c) 2014 Alex Rice. All rights reserved.
//
import UIKit
import CoreLocation
var patchListGlobal : [AnyObject] = []
var debug = true
class PatchListViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var patchListView: UITableView!
var storage = NSUserDefaults.standardUserDefaults()
var today = NSDate()
var cal = NSCalendar(calendarIdentifier: "gregorian")
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
patchListView.dataSource = self
var storage = NSUserDefaults.standardUserDefaults()
if let frozenPLG = storage.objectForKey("ForagerPatchList") as? NSData {
var thawedPLG = NSKeyedUnarchiver.unarchiveObjectWithData(frozenPLG) as [Patch]
patchListGlobal = thawedPLG
println("unthawed")
for patch in patchListGlobal {
println("Patch of: \(patch.plantName!)")
}
} else {
println("nothing to thaw")
}
switch CLLocationManager.authorizationStatus() {
case .Authorized:
println("authorized")
case .AuthorizedWhenInUse:
println("authorized when in use")
case .Restricted:
println("restricted")
var permissionAlert = UIAlertView(title: "Location Data", message: "Forager is unable to access your location data, so map functions may not work as expected", delegate: self, cancelButtonTitle: "ok")
permissionAlert.show()
case .NotDetermined:
println("not determined")
locationManager.requestWhenInUseAuthorization()
println("asked")
case .Denied:
println("denied")
var permissionAlert = UIAlertView(title: "Location Data", message: "Forager needs your location data so that we can show you the correct map area.\nThings are going to be jankey unless you go to Settings and turn on Location Services", delegate: self, cancelButtonTitle: "ok")
permissionAlert.show()
}
let addNewButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addButtonPressed")
self.navigationItem.rightBarButtonItem = addNewButton
}
func addButtonPressed() {
self.performSegueWithIdentifier("toNew", sender: self)
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return patchListGlobal.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("patchCell") as UITableViewCell
let item = patchListGlobal[indexPath.row] as Patch
cell.textLabel.text = item.plantName
var harvest = (patchListGlobal[indexPath.row] as Patch).nextHarvest //here's that casting bug again
if (harvest == harvest.earlierDate(today)){
cell.detailTextLabel.text = "Ripe"
} else {
var comparison = cal.components(NSCalendarUnit.DayCalendarUnit, fromDate: today, toDate: item.nextHarvest, options: nil)
var daysLeft = comparison.day
if daysLeft == 0 {
cell.detailTextLabel.text = "Ready today"
} else {
cell.detailTextLabel.text = "Ready in \(daysLeft) days"
}
}
return cell
}
func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
patchListGlobal.removeAtIndex(indexPath.row)
var serializedPLG = NSKeyedArchiver.archivedDataWithRootObject(patchListGlobal)
storage.setObject(serializedPLG, forKey: "ForagerPatchList")
storage.synchronize()
println("saved")
let indexPaths = [indexPath]
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic)
}
override func viewWillAppear(animated: Bool) {
patchListView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "toDetailView" {
var dest = segue.destinationViewController as PatchDetailViewController
dest.hidesBottomBarWhenPushed = true
let indexPath = self.patchListView.indexPathForSelectedRow()
let patch = patchListGlobal[indexPath.row] as Patch
let detailView = segue.destinationViewController as PatchDetailViewController
detailView.lat = patch.lat
detailView.lon = patch.lon
detailView.plantName = patch.plantName
detailView.nextHarvest = patch.nextHarvest
} else if segue.identifier == "toNew" {
var dest = segue.destinationViewController as NewPatchViewController
dest.hidesBottomBarWhenPushed = true
}
}
}
|
mit
|
a88fc37b71617391e466f2ede6eb4e08
| 39.492188 | 288 | 0.660042 | 5.398958 | false | false | false | false |
kesun421/firefox-ios
|
Client/Frontend/Widgets/PhotonActionSheet.swift
|
1
|
20199
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Storage
import SnapKit
import Shared
private struct PhotonActionSheetUX {
static let MaxWidth: CGFloat = 414
static let Padding: CGFloat = 10
static let SectionVerticalPadding: CGFloat = 13
static let HeaderHeight: CGFloat = 80
static let RowHeight: CGFloat = 44
static let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor(rgb: 0x353535)
static let DescriptionLabelColor = UIColor(rgb: 0x919191)
static let PlaceholderImage = UIImage(named: "defaultTopSiteIcon")
static let BorderWidth: CGFloat = 0.5
static let BorderColor = UIColor(white: 0, alpha: 0.1)
static let CornerRadius: CGFloat = 10
static let SiteImageViewSize = 52
static let IconSize = CGSize(width: 24, height: 24)
static let HeaderName = "PhotonActionSheetHeaderView"
static let CellName = "PhotonActionSheetCell"
static let CancelButtonHeight: CGFloat = 56
static let TablePadding: CGFloat = 6
}
public struct PhotonActionSheetItem {
public fileprivate(set) var title: String
public fileprivate(set) var iconString: String
public fileprivate(set) var isEnabled: Bool // Used by toggles like nightmode to switch tint color
public fileprivate(set) var handler: ((PhotonActionSheetItem) -> Void)?
init(title: String, iconString: String, isEnabled: Bool = false, handler: ((PhotonActionSheetItem) -> Void)?) {
self.title = title
self.iconString = iconString
self.isEnabled = isEnabled
self.handler = handler
}
}
private enum PresentationStyle {
case centered // used in the home panels
case bottom // used to display the menu
}
class PhotonActionSheet: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
fileprivate(set) var actions: [[PhotonActionSheetItem]]
private var site: Site?
private let style: PresentationStyle
private lazy var showCancelButton: Bool = {
return self.style == .bottom && self.modalPresentationStyle != .popover
}()
var tableView = UITableView(frame: CGRect.zero, style: .grouped)
private var tintColor = UIColor(rgb: 0x272727)
private var outerScrollView = UIScrollView()
lazy var tapRecognizer: UITapGestureRecognizer = {
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: #selector(PhotonActionSheet.dismiss(_:)))
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.cancelsTouchesInView = false
tapRecognizer.delegate = self
return tapRecognizer
}()
lazy var cancelButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.CancelButtonTitle, for: .normal)
button.backgroundColor = UIConstants.AppBackgroundColor
button.setTitleColor(UIConstants.SystemBlueColor, for: .normal)
button.layer.cornerRadius = PhotonActionSheetUX.CornerRadius
button.titleLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontExtraLargeBold
button.addTarget(self, action: #selector(PhotonActionSheet.dismiss(_:)), for: .touchUpInside)
button.accessibilityIdentifier = "PhotonMenu.cancel"
return button
}()
init(site: Site, actions: [PhotonActionSheetItem]) {
self.site = site
self.actions = [actions]
self.style = .centered
super.init(nibName: nil, bundle: nil)
}
init(actions: [[PhotonActionSheetItem]]) {
self.actions = actions
self.style = .bottom
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var photonTransitionDelegate: UIViewControllerTransitioningDelegate? {
didSet {
self.transitioningDelegate = photonTransitionDelegate
}
}
override func viewDidLoad() {
super.viewDidLoad()
if style == .centered {
applyBackgroundBlur()
self.tintColor = UIConstants.SystemBlueColor
}
view.addGestureRecognizer(tapRecognizer)
view.addSubview(tableView)
view.accessibilityIdentifier = "Action Sheet"
tableView.bounces = false
tableView.delegate = self
tableView.dataSource = self
tableView.sectionFooterHeight = 0
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
tableView.register(PhotonActionSheetCell.self, forCellReuseIdentifier: PhotonActionSheetUX.CellName)
tableView.register(PhotonActionSheetHeaderView.self, forHeaderFooterViewReuseIdentifier: PhotonActionSheetUX.HeaderName)
tableView.register(PhotonActionSheetSeparator.self, forHeaderFooterViewReuseIdentifier: "SeparatorSectionHeader")
tableView.isScrollEnabled = true
tableView.showsVerticalScrollIndicator = false
tableView.layer.cornerRadius = PhotonActionSheetUX.CornerRadius
tableView.separatorStyle = .none
tableView.cellLayoutMarginsFollowReadableWidth = false
tableView.accessibilityIdentifier = "Context Menu"
let footer = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: tableView.frame.width, height: PhotonActionSheetUX.TablePadding)))
tableView.tableFooterView = footer
tableView.tableHeaderView = footer.clone()
// In a popover the popover provides the blur background
// Not using a background color allows the view to style correctly with the popover arrow
if self.popoverPresentationController == nil {
tableView.backgroundColor = UIConstants.AppBackgroundColor.withAlphaComponent(0.7)
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
tableView.backgroundView = blurEffectView
} else {
tableView.backgroundColor = .clear
}
let width = min(self.view.frame.size.width, PhotonActionSheetUX.MaxWidth) - (PhotonActionSheetUX.Padding * 2)
let height = actionSheetHeight()
if self.modalPresentationStyle == .popover {
self.preferredContentSize = CGSize(width: width, height: height)
}
if self.showCancelButton {
self.view.addSubview(cancelButton)
cancelButton.snp.makeConstraints { make in
make.centerX.equalTo(self.view.snp.centerX)
make.width.equalTo(width)
make.height.equalTo(PhotonActionSheetUX.CancelButtonHeight)
if #available(iOS 11, *) {
let bottomPad: CGFloat
if let window = UIApplication.shared.keyWindow, window.safeAreaInsets.bottom != 0 {
// for iPhone X and similar
bottomPad = 0
} else {
bottomPad = PhotonActionSheetUX.Padding
}
make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-bottomPad)
} else {
make.bottom.equalTo(self.view.snp.bottom).offset(-PhotonActionSheetUX.Padding)
}
}
}
if style == .bottom && self.modalPresentationStyle == .popover {
// We are showing the menu in a popOver
self.actions = actions.map({ $0.reversed() }).reversed()
tableView.frame = CGRect(origin: CGPoint.zero, size: self.preferredContentSize)
return
}
tableView.snp.makeConstraints { make in
make.centerX.equalTo(self.view.snp.centerX)
switch style {
case .bottom:
make.bottom.equalTo(cancelButton.snp.top).offset(-PhotonActionSheetUX.Padding)
case .centered:
make.centerY.equalTo(self.view.snp.centerY)
}
make.width.equalTo(width)
make.height.equalTo(min(height, view.bounds.height - PhotonActionSheetUX.CancelButtonHeight - (PhotonActionSheetUX.Padding * 6)))
}
}
private func applyBackgroundBlur() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let screenshot = appDelegate.window?.screenshot() {
let blurredImage = screenshot.applyBlur(withRadius: 5,
blurType: BOXFILTER,
tintColor: UIColor.black.withAlphaComponent(0.2),
saturationDeltaFactor: 1.8,
maskImage: nil)
let imageView = UIImageView(image: blurredImage)
view.addSubview(imageView)
}
}
fileprivate func actionSheetHeight() -> CGFloat {
let count = actions.reduce(0) { $1.count + $0 }
let headerHeight = (style == .centered) ? PhotonActionSheetUX.HeaderHeight : 0
let separatorHeight = actions.count > 1 ? (actions.count - 1) * Int(PhotonActionSheetUX.SectionVerticalPadding) : 0
return CGFloat(separatorHeight) + headerHeight + ( PhotonActionSheetUX.TablePadding * 2) + CGFloat(count) * PhotonActionSheetUX.RowHeight
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func dismiss(_ gestureRecognizer: UIGestureRecognizer?) {
self.dismiss(animated: true, completion: nil)
}
deinit {
tableView.dataSource = nil
tableView.delegate = nil
}
override func updateViewConstraints() {
if !self.showCancelButton {
tableView.frame = CGRect(origin: CGPoint.zero, size: self.preferredContentSize)
}
super.updateViewConstraints()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if self.traitCollection.verticalSizeClass != previousTraitCollection?.verticalSizeClass
|| self.traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass {
updateViewConstraints()
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if tableView.frame.contains(touch.location(in: self.view)) {
return false
}
return true
}
func numberOfSections(in tableView: UITableView) -> Int {
return actions.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions[section].count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let action = actions[indexPath.section][indexPath.row]
guard let handler = action.handler else {
self.dismiss(nil)
return
}
self.dismiss(nil)
return handler(action)
}
func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return PhotonActionSheetUX.RowHeight
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// If we have multiple sections show a separator for each one except the first.
if section > 0 {
return PhotonActionSheetUX.SectionVerticalPadding
}
return self.site != nil ? PhotonActionSheetUX.HeaderHeight : 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PhotonActionSheetUX.CellName, for: indexPath) as! PhotonActionSheetCell
let action = actions[indexPath.section][indexPath.row]
cell.accessibilityIdentifier = action.iconString
cell.tintColor = action.isEnabled ? UIConstants.SystemBlueColor : self.tintColor
cell.configureCell(action.title, imageString: action.iconString)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// If we have multiple sections show a separator for each one except the first.
if section > 0 {
return tableView.dequeueReusableHeaderFooterView(withIdentifier: "SeparatorSectionHeader")
}
guard let site = site else {
return nil
}
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: PhotonActionSheetUX.HeaderName) as! PhotonActionSheetHeaderView
header.tintColor = self.tintColor
header.configureWithSite(site)
return header
}
}
private class PhotonActionSheetHeaderView: UITableViewHeaderFooterView {
static let Padding: CGFloat = 12
static let VerticalPadding: CGFloat = 2
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.MediumSizeBoldFontAS
titleLabel.textAlignment = .left
titleLabel.numberOfLines = 2
return titleLabel
}()
lazy var descriptionLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.MediumSizeRegularWeightAS
titleLabel.textAlignment = .left
titleLabel.numberOfLines = 1
return titleLabel
}()
lazy var siteImageView: UIImageView = {
let siteImageView = UIImageView()
siteImageView.contentMode = UIViewContentMode.center
siteImageView.clipsToBounds = true
siteImageView.layer.cornerRadius = PhotonActionSheetUX.CornerRadius
siteImageView.layer.borderColor = PhotonActionSheetUX.BorderColor.cgColor
siteImageView.layer.borderWidth = PhotonActionSheetUX.BorderWidth
return siteImageView
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView = UIView()
self.backgroundView?.backgroundColor = .clear
contentView.addSubview(siteImageView)
siteImageView.snp.remakeConstraints { make in
make.centerY.equalTo(contentView)
make.leading.equalTo(contentView).offset(PhotonActionSheetHeaderView.Padding)
make.size.equalTo(PhotonActionSheetUX.SiteImageViewSize)
}
let stackView = UIStackView(arrangedSubviews: [titleLabel, descriptionLabel])
stackView.spacing = PhotonActionSheetHeaderView.VerticalPadding
stackView.alignment = .leading
stackView.axis = .vertical
contentView.addSubview(stackView)
stackView.snp.makeConstraints { make in
make.leading.equalTo(siteImageView.snp.trailing).offset(PhotonActionSheetHeaderView.Padding)
make.trailing.equalTo(contentView).inset(PhotonActionSheetHeaderView.Padding)
make.centerY.equalTo(siteImageView.snp.centerY)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
self.siteImageView.image = nil
self.siteImageView.backgroundColor = UIColor.clear
}
func configureWithSite(_ site: Site) {
self.siteImageView.setFavicon(forSite: site) { (color, url) in
self.siteImageView.backgroundColor = color
self.siteImageView.image = self.siteImageView.image?.createScaled(PhotonActionSheetUX.IconSize)
}
self.titleLabel.text = site.title.characters.count <= 1 ? site.url : site.title
self.descriptionLabel.text = site.tileURL.baseDomain
}
}
private struct PhotonActionSheetCellUX {
static let LabelColor = UIConstants.SystemBlueColor
static let BorderWidth: CGFloat = CGFloat(0.5)
static let CellSideOffset = 20
static let TitleLabelOffset = 10
static let CellTopBottomOffset = 12
static let StatusIconSize = 24
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let CornerRadius: CGFloat = 3
}
private class PhotonActionSheetSeparator: UITableViewHeaderFooterView {
let separatorLineView = UIView()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView = UIView()
self.backgroundView?.backgroundColor = .clear
separatorLineView.backgroundColor = UIColor.lightGray
self.contentView.addSubview(separatorLineView)
separatorLineView.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.centerY.equalTo(self)
make.height.equalTo(0.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class PhotonActionSheetCell: UITableViewCell {
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS
titleLabel.minimumScaleFactor = 0.75 // Scale the font if we run out of space
titleLabel.textColor = PhotonActionSheetCellUX.LabelColor
titleLabel.textAlignment = .left
titleLabel.numberOfLines = 1
titleLabel.adjustsFontSizeToFitWidth = true
return titleLabel
}()
lazy var statusIcon: UIImageView = {
let siteImageView = UIImageView()
siteImageView.contentMode = UIViewContentMode.scaleAspectFit
siteImageView.clipsToBounds = true
siteImageView.layer.cornerRadius = PhotonActionSheetCellUX.CornerRadius
return siteImageView
}()
lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = PhotonActionSheetCellUX.SelectedOverlayColor
selectedOverlay.isHidden = true
return selectedOverlay
}()
override var isSelected: Bool {
didSet {
self.selectedOverlay.isHidden = !isSelected
}
}
override func prepareForReuse() {
self.statusIcon.image = nil
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
isAccessibilityElement = true
contentView.addSubview(selectedOverlay)
contentView.addSubview(titleLabel)
contentView.addSubview(statusIcon)
backgroundColor = .clear
selectedOverlay.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(statusIcon.snp.trailing).offset(16)
make.trailing.equalTo(contentView)
make.centerY.equalTo(contentView)
}
statusIcon.snp.makeConstraints { make in
make.size.equalTo(PhotonActionSheetCellUX.StatusIconSize)
make.leading.equalTo(contentView).offset(16)
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureCell(_ label: String, imageString: String) {
titleLabel.text = label
titleLabel.textColor = self.tintColor
accessibilityIdentifier = imageString
accessibilityLabel = label
if let image = UIImage(named: imageString)?.withRenderingMode(.alwaysTemplate) {
statusIcon.image = image
statusIcon.tintColor = self.tintColor
}
}
}
|
mpl-2.0
|
61571196c49e1f89ebed17d9165f6703
| 39.72379 | 150 | 0.665033 | 5.471018 | false | false | false | false |
wikimedia/wikipedia-ios
|
WMF Framework/CacheFileWriterHelper.swift
|
1
|
5580
|
import Foundation
enum CacheFileWriterHelperError: Error {
case unexpectedHeaderFieldsType
}
final class CacheFileWriterHelper {
static func fileURL(for key: String) -> URL {
return CacheController.cacheURL.appendingPathComponent(key, isDirectory: false)
}
static func saveData(data: Data, toNewFileWithKey key: String, completion: @escaping (FileSaveResult) -> Void) {
do {
let newFileURL = self.fileURL(for: key)
try data.write(to: newFileURL)
completion(.success)
} catch let error as NSError {
if error.domain == NSCocoaErrorDomain, error.code == NSFileWriteFileExistsError {
completion(.exists)
} else {
completion(.failure(error))
}
} catch let error {
completion(.failure(error))
}
}
static func copyFile(from fileURL: URL, toNewFileWithKey key: String, completion: @escaping (FileSaveResult) -> Void) {
do {
let newFileURL = self.fileURL(for: key)
try FileManager.default.copyItem(at: fileURL, to: newFileURL)
completion(.success)
} catch let error as NSError {
if error.domain == NSCocoaErrorDomain, error.code == NSFileWriteFileExistsError {
completion(.exists)
} else {
completion(.failure(error))
}
} catch let error {
completion(.failure(error))
}
}
static func saveResponseHeader(httpUrlResponse: HTTPURLResponse, toNewFileName fileName: String, completion: @escaping (FileSaveResult) -> Void) {
guard let headerFields = httpUrlResponse.allHeaderFields as? [String: String] else {
completion(.failure(CacheFileWriterHelperError.unexpectedHeaderFieldsType))
return
}
saveResponseHeader(headerFields: headerFields, toNewFileName: fileName, completion: completion)
}
static func saveResponseHeader(headerFields: [String: String], toNewFileName fileName: String, completion: (FileSaveResult) -> Void) {
do {
let contentData: Data = try NSKeyedArchiver.archivedData(withRootObject: headerFields, requiringSecureCoding: false)
let newFileURL = self.fileURL(for: fileName)
try contentData.write(to: newFileURL)
completion(.success)
} catch let error as NSError {
if error.domain == NSCocoaErrorDomain, error.code == NSFileWriteFileExistsError {
completion(.exists)
} else {
completion(.failure(error))
}
} catch let error {
completion(.failure(error))
}
}
static func replaceResponseHeaderWithURLResponse(_ httpUrlResponse: HTTPURLResponse, atFileName fileName: String, completion: @escaping (FileSaveResult) -> Void) {
guard let headerFields = httpUrlResponse.allHeaderFields as? [String: String] else {
completion(.failure(CacheFileWriterHelperError.unexpectedHeaderFieldsType))
return
}
replaceResponseHeaderWithHeaderFields(headerFields, atFileName: fileName, completion: completion)
}
static func replaceResponseHeaderWithHeaderFields(_ headerFields:[String: String], atFileName fileName: String, completion: @escaping (FileSaveResult) -> Void) {
do {
let headerData: Data = try NSKeyedArchiver.archivedData(withRootObject: headerFields, requiringSecureCoding:false)
replaceFileWithData(headerData, fileName: fileName, completion: completion)
} catch let error {
completion(.failure(error))
}
}
static func replaceFileWithData(_ data: Data, fileName: String, completion: @escaping (FileSaveResult) -> Void) {
let destinationURL = fileURL(for: fileName)
do {
let temporaryDirectoryURL = try FileManager.default.url(for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: destinationURL,
create: true)
let temporaryFileName = UUID().uuidString
let temporaryFileURL = temporaryDirectoryURL.appendingPathComponent(temporaryFileName)
try data.write(to: temporaryFileURL,
options: .atomic)
_ = try FileManager.default.replaceItemAt(destinationURL, withItemAt: temporaryFileURL)
try FileManager.default.removeItem(at: temporaryDirectoryURL)
completion(.success)
} catch let error {
completion(.failure(error))
}
}
static func saveContent(_ content: String, toNewFileName fileName: String, completion: @escaping (FileSaveResult) -> Void) {
do {
let newFileURL = self.fileURL(for: fileName)
try content.write(to: newFileURL, atomically: true, encoding: .utf8)
completion(.success)
} catch let error as NSError {
if error.domain == NSCocoaErrorDomain, error.code == NSFileWriteFileExistsError {
completion(.exists)
} else {
completion(.failure(error))
}
} catch let error {
completion(.failure(error))
}
}
}
enum FileSaveResult {
case exists
case success
case failure(Error)
}
|
mit
|
406ec12b2d2b6c0482702d19378625e9
| 39.143885 | 167 | 0.61129 | 5.508391 | false | false | false | false |
flexih/CorePlayer.Swift
|
CorePlayerDemo/ModuleView.swift
|
1
|
2867
|
//
// ModuleView.swift
// CorePlayer
//
// Created by flexih on 4/28/15.
// Copyright (c) 2015 flexih. All rights reserved.
//
import UIKit
class ModuleView: CPModuleView {
let button = UIButton()
func willPlay() {
NSLog("willplay")
}
override func layoutView() {
self.frame = CGRectMake(0, 0, 100, 50)
}
override func layoutSubviews() {
super.layoutSubviews()
button.frame = self.bounds
}
override func initModule() {
NSLog("initModule")
button.backgroundColor = UIColor.blueColor()
button.addTarget(self, action: #selector(ModuleView.buttonClicked), forControlEvents: UIControlEvents.TouchUpInside)
button.setTitle("Pause", forState: UIControlState.Normal)
button.setTitle("Play", forState: UIControlState.Selected)
self.addSubview(button)
self.moduleDelegate?.view().addSubview(self)
}
func buttonClicked() {
button.selected = !button.selected
if self.moduleDelegate!.isPlaying() {
self.moduleDelegate?.pause()
} else {
self.moduleDelegate?.play()
}
}
override func deinitModule() {
NSLog("deinitModule")
}
func startPlay() {
NSLog("startPlay")
}
func cancelPlay() {
NSLog("cancelPlay")
}
func endPlayCode(state: CPState) {
NSLog("endPlayCode")
}
func willSection(cpu: CPURL) {
NSLog("willSection")
}
func startSection(cpu: CPURL) {
NSLog("startSection")
}
func endSection(cpu: CPURL) {
NSLog("endSection")
}
func willPend() {
NSLog("willPend")
}
func endPend() {
NSLog("endPend")
}
func willPause() {
NSLog("willPause")
}
func endPause() {
NSLog("endPause")
}
func startSeek(time: NSTimeInterval) {
NSLog("startSeek")
}
func seekTo(time: NSTimeInterval) {
NSLog("seekTo")
}
func endSeek(time: NSTimeInterval, isEnd: Bool) {
NSLog("endSeek")
}
func durationAvailable(duration: NSTimeInterval) {
NSLog("durationAvailable")
}
func played(duration: NSTimeInterval) {
NSLog("played")
}
func playable(duration: NSTimeInterval) {
NSLog("playable")
}
func appResign() {
NSLog("appResign")
}
func appActive() {
NSLog("appActive")
}
func presentationSize(size: CGSize) {
NSLog("presentationSize")
}
func airplayShift(on: Bool) {
NSLog("airplayShift")
}
func interrupt(reason: InterruptionReason) {
NSLog("interrupt")
}
func error(err: Int) {
NSLog("error")
}
}
|
mit
|
1bfff980ee074d2fddbdaca7d77cfb97
| 19.625899 | 124 | 0.555284 | 4.390505 | false | false | false | false |
Eonil/SQLite3
|
Sources/LowLevel/Core.Result.swift
|
2
|
6634
|
//
// Core.Status.swift
// EonilSQLite3
//
// Created by Hoon H. on 9/16/14.
//
//
import Foundation
extension Core
{
// struct ResultCode
// {
// let value:Int32
//
// static let OK = ResultCode(value: SQLITE_OK)
// static let Error = ResultCode(value: SQLITE_ERROR)
// static let Internal = ResultCode(value: SQLITE_INTERNAL)
// static let Permission = ResultCode(value: SQLITE_PERM)
// static let Abort = ResultCode(value: SQLITE_ABORT)
// static let Busy = ResultCode(value: SQLITE_BUSY)
// static let Locked = ResultCode(value: SQLITE_LOCKED)
// static let NoMemory = ResultCode(value: SQLITE_NOMEM)
// static let Readonly = ResultCode(value: SQLITE_READONLY)
// static let Interrupt = ResultCode(value: SQLITE_INTERRUPT)
// static let IOError = ResultCode(value: SQLITE_IOERR)
// static let Corrupt = ResultCode(value: SQLITE_CORRUPT)
// static let Corrupt = ResultCode(value: SQLITE_CORRUPT)
// static let Corrupt = ResultCode(value: SQLITE_CORRUPT)
// static let Corrupt = ResultCode(value: SQLITE_CORRUPT)
// static let Corrupt = ResultCode(value: SQLITE_CORRUPT)
// static let Corrupt = ResultCode(value: SQLITE_CORRUPT)
// static let Corrupt = ResultCode(value: SQLITE_CORRUPT)
// }
// #define SQLITE_OK 0 /* Successful result */
// /* beginning-of-error-codes */
// #define SQLITE_ERROR 1 /* SQL error or missing database */
// #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
// #define SQLITE_PERM 3 /* Access permission denied */
// #define SQLITE_ABORT 4 /* Callback routine requested an abort */
// #define SQLITE_BUSY 5 /* The database file is locked */
// #define SQLITE_LOCKED 6 /* A table in the database is locked */
// #define SQLITE_NOMEM 7 /* A malloc() failed */
// #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
// #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
// #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
// #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
// #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
// #define SQLITE_FULL 13 /* Insertion failed because database is full */
// #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
// #define SQLITE_PROTOCOL 15 /* Connection lock protocol error */
// #define SQLITE_EMPTY 16 /* Connection is empty */
// #define SQLITE_SCHEMA 17 /* The database schema changed */
// #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
// #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
// #define SQLITE_MISMATCH 20 /* Data type mismatch */
// #define SQLITE_MISUSE 21 /* Library used incorrectly */
// #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
// #define SQLITE_AUTH 23 /* Authorization denied */
// #define SQLITE_FORMAT 24 /* Auxiliary database format error */
// #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
// #define SQLITE_NOTADB 26 /* File opened that is not a database file */
// #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
// #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
// /* end-of-error-codes */
//
// /*
// ** CAPI3REF: Extended Result Codes
// ** KEYWORDS: {extended error code} {extended error codes}
// ** KEYWORDS: {extended result code} {extended result codes}
// **
// ** In its default configuration, SQLite API routines return one of 26 integer
// ** [SQLITE_OK | result codes]. However, experience has shown that many of
// ** these result codes are too coarse-grained. They do not provide as
// ** much information about problems as programmers might like. In an effort to
// ** address this, newer versions of SQLite (version 3.3.8 and later) include
// ** support for additional result codes that provide more detailed information
// ** about errors. The extended result codes are enabled or disabled
// ** on a per database connection basis using the
// ** [sqlite3_extended_result_codes()] API.
// **
// ** Some of the available extended result codes are listed here.
// ** One may expect the number of extended result codes will be expand
// ** over time. Software that uses extended result codes should expect
// ** to see new result codes in future releases of SQLite.
// **
// ** The SQLITE_OK result code will never be extended. It will always
// ** be exactly zero.
// */
// #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
// #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
// #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
// #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
// #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
// #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
// #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
// #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
// #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
// #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
// #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
// #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
// #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
// #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
// #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
// #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
// #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
// #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
// #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
// #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
// #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
// #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
// #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
// #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
// #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
// #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
// #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
// #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
// #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
// #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
}
|
mit
|
966c8f65bc5ccb8d260087cdcb469a4c
| 53.377049 | 83 | 0.641845 | 3.220388 | false | false | false | false |
MaddTheSane/SpaceEvaders
|
SpaceEvaders/OptionsMenu.swift
|
1
|
701
|
import SpriteKit
class OptionsMenu {
init(menu: SKNode, size: CGSize) {
let options = ["sound", "music", "follow", "indicators"]
var pos: CGFloat = 51
for option in options {
addOption(menu, size: size, option: option, pos: pos)
pos -= 5
}
}
func addOption(menu: SKNode, size: CGSize, option: String, pos: CGFloat) {
let height = size.height
let isOn = Options.option.get(option) ? "on" : "off"
let sprite = Sprite(named: "\(option)\(isOn)", x: size.width * pos / 60, y: 4 * height / 5, size: CGSizeMake(height / 12, height / 12))
sprite.name = "option_\(option)"
sprite.addTo(menu)
}
}
|
mit
|
eb9a710579bcf93204f1581a0fc856b7
| 34.05 | 143 | 0.564907 | 3.728723 | false | false | false | false |
austinzheng/swift-compiler-crashes
|
crashes-duplicates/27271-swift-typechecker-validatedecl.swift
|
4
|
2305
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A : P {func a
class
b : A
func a{
{{struct d B {
struct c<T where f
struct b
class B<T where k:d B : A{
f
class a: e{enum S<T
class B<T=a{enum S<I : b : b
struct B<d { }
let a
}
let a{
class d{
b {
class b{enum e
protocol c<T where k:d=[Void{
class d=a{
class C<A{}
class A
let a
}
}
}
}protocol a {class a{
}
}}}
}
protocol a {
let f<T where H:d where H:a{{typealias d:T=Dictionary<T where T{
if true {
protocol P{
f=[]
struct B<S<S<T where H:NSObject
<T where j: a:a{
struct Q<T where H:b<T : P {}
var b : a{
l
let:NSObject
class A{
var f: a{}
var b : T where f<d { }protocol c {func a{
}
{
struct c{
class C<I : e{
var _=B{func a:{
class A
struct c
class A{
"" \(a{enum S<c<T where H:SequenceType
class B<T=k
a {
class d=k
}
var
class
protocol c<T where I : a{
class d=[Void{
class d{func p )"[ 0
class A
}
}}
let
func f {}
class d{enum C<T where j: b {
struct c<T where j: e{
enum S<T where d=[Void{
}class d{
class b:{let f=[]
protocol c
var f:T>
f:a{
class d:c
func p )"" "[ 0
f: A{
func x(a<T{
let:{
<d { }{
enum S<T : A{struct B<k
}
let:a:a{
T where d{
struct S
}
{
class d{
}
class A {
{
if true{
}{
Void{
class A : A {
}
}
}}
class b{
class d:SequenceType
}func b{}protocol P{
class d=c
}
let
{
struct d:CollectionType
}
protocol c : Poid{
let f
let:T{
class b<T where g:CollectionType
func a<T : a{
let f
class B{
}
class b{
var a
struct d=c{struct B{
class C{
f:CollectionType
class A{struct B<T where H:SequenceType
var a:a{
class a{
func x(a<T : b:a= []
let a{
class B
}
protocol c<T where I : a{
enum S
protocol c<T where H:{
}
let f:CollectionType
enum S< > S >
class d}{struct B
protocol c {
f
class A
protocol c
}}}
struct Q<h where I : A{
}
f=a{struct B{
enum S<
class C<
func a{enum e
{
protocol P{struct c<T>Bool [ 0
func x(a{typealias d=c
class B<T>
class A{
func x(a<T where j: e A {struct d{}struct Q<c<T where d}
T where f:T=[Void{}
{
}
enum e{
protocol c{}
class b{
var f
let c<T where T>i<a
class a{
let a
protocol c {
class a<h where j: A : A{
struct S<T{
struct d{
struct B{
}
func x(a{
let a
class a<T where h:{
protocol A {
}
f=[Void{
{
let a{
<T where h:T
let
struct S< {let f:CollectionType
{
let
|
mit
|
b39924653d1b20f847e0692646a1ee00
| 11.459459 | 87 | 0.641215 | 2.307307 | false | false | false | false |
mozilla-mobile/focus
|
XCUITest/SettingAppearanceTest.swift
|
1
|
7945
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
class SettingAppearanceTest: BaseTestCase {
override func setUp() {
super.setUp()
dismissFirstRunUI()
}
override func tearDown() {
app.terminate()
super.tearDown()
}
// Check for the basic appearance of the Settings Menu
func testCheckSetting() {
waitforHittable(element: app.buttons["Settings"])
app.buttons["Settings"].tap()
// Check About page
app.tables.firstMatch.swipeUp()
let aboutCell = app.cells["settingsViewController.about"]
waitforHittable(element: aboutCell)
aboutCell.tap()
let tablesQuery = app.tables
// Check Help page, wait until the webpage is shown
waitforHittable(element: tablesQuery.staticTexts["Help"])
tablesQuery.staticTexts["Help"].tap()
app.navigationBars.buttons.element(boundBy: 0).tap()
// Check Your Rights page, until the text is displayed
tablesQuery.staticTexts["Your Rights"].tap()
app.navigationBars.buttons.element(boundBy: 0).tap()
// Go back to Settings
app.navigationBars.buttons.element(boundBy: 0).tap()
//Check the initial state of the switch values
let safariSwitch = app.tables.switches["Safari"]
XCTAssertEqual(safariSwitch.value as! String, "0")
safariSwitch.tap()
// Check the information page
XCTAssert(app.staticTexts["Open Settings App"].exists)
XCTAssert(app.staticTexts["Tap Safari, then select Content Blockers"].exists)
if app.label == "Firefox Focus" {
XCTAssert(app.staticTexts["Firefox Focus is not enabled."].exists)
XCTAssert(app.staticTexts["Enable Firefox Focus"].exists)
app.navigationBars.buttons.element(boundBy: 0).tap()
} else {
XCTAssert(app.staticTexts["Firefox Klar is not enabled."].exists)
XCTAssert(app.staticTexts["Enable Firefox Klar"].exists)
app.navigationBars.buttons.element(boundBy: 0).tap()
}
XCTAssertEqual(app.tables.switches["BlockerToggle.BlockFonts"].value as! String, "0")
if app.label == "Firefox Focus" {
XCTAssertEqual(app.tables.switches["BlockerToggle.SendAnonymousUsageData"].value as! String, "1")
} else {
XCTAssertEqual(app.tables.switches["BlockerToggle.SendAnonymousUsageData"].value as! String, "0")
}
// Check Tracking Protection Settings page
app.tables.firstMatch.swipeDown()
let trackingProtectionCell = app.cells["settingsViewController.trackingCell"]
waitforHittable(element: trackingProtectionCell)
trackingProtectionCell.tap()
XCTAssertEqual(app.tables.switches["BlockerToggle.BlockAds"].value as! String, "1")
XCTAssertEqual(app.tables.switches["BlockerToggle.BlockAnalytics"].value as! String, "1")
XCTAssertEqual(app.tables.switches["BlockerToggle.BlockSocial"].value as! String, "1")
let otherContentSwitch = app.tables.switches["BlockerToggle.BlockOther"]
XCTAssertEqual(otherContentSwitch.value as! String, "0")
otherContentSwitch.tap()
let alertsQuery = app.alerts
// Say yes this time, the switch should be enabled
alertsQuery.buttons["I Understand"].tap()
XCTAssertEqual(otherContentSwitch.value as! String, "1")
otherContentSwitch.tap()
// Say No this time, the switch should remain disabled
otherContentSwitch.tap()
alertsQuery.buttons["No, Thanks"].tap()
XCTAssertEqual(otherContentSwitch.value as! String, "0")
// Go back to settings
app.navigationBars.buttons.element(boundBy: 0).tap()
// Check navigate to app store review and back
let reviewCell = app.cells["settingsViewController.rateFocus"]
let safariApp = XCUIApplication(privateWithPath: nil, bundleID: "com.apple.mobilesafari")!
app.tables.firstMatch.swipeUp()
waitforHittable(element: reviewCell)
reviewCell.tap()
waitforExistence(element: safariApp)
XCTAssert(safariApp.state == .runningForeground)
app.activate()
}
func testOpenInSafari() {
let safariapp = XCUIApplication(privateWithPath: nil, bundleID: "com.apple.mobilesafari")!
loadWebPage("https://www.google.com", waitForLoadToFinish: true)
waitforHittable(element: app.buttons["URLBar.pageActionsButton"])
app.buttons["URLBar.pageActionsButton"].tap()
let safariButton = app.cells["Open in Safari"]
waitforHittable(element: safariButton)
safariButton.tap()
// Now in Safari
let safariLabel = safariapp.otherElements["Address"]
waitForValueContains(element: safariLabel, value: "google")
// Go back to Focus
app.activate()
// Now back to Focus
waitForWebPageLoad()
app.buttons["URLBar.deleteButton"].tap()
waitforExistence(element: app.staticTexts["Your browsing history has been erased."])
}
func testDisableAutocomplete() {
// Navigate to Settings
waitforHittable(element: app.buttons["Settings"])
app.buttons["Settings"].tap()
// Navigate to Autocomplete Settings
waitforHittable(element: app.tables.cells["SettingsViewController.autocompleteCell"])
app.tables.cells["SettingsViewController.autocompleteCell"].tap()
// Verify that autocomplete is enabled
waitforExistence(element: app.tables.switches["toggleAutocompleteSwitch"])
let toggle = app.tables.switches["toggleAutocompleteSwitch"]
XCTAssertEqual(toggle.value as! String, "1")
// Turn autocomplete off
toggle.tap()
XCTAssertEqual(toggle.value as! String, "0")
// Turn autocomplete back on
toggle.tap()
}
func testAddRemoveCustomDomain() {
// Navigate to Settings
waitforHittable(element: app.buttons["Settings"])
app.buttons["Settings"].tap()
// Navigate to Autocomplete Settings
waitforHittable(element: app.tables.cells["SettingsViewController.autocompleteCell"])
app.tables.cells["SettingsViewController.autocompleteCell"].tap()
// Navigate to the customURL list
waitforHittable(element: app.tables.cells["customURLS"])
app.tables.cells["customURLS"].tap()
// Navigate to add domain screen
waitforHittable(element: app.tables.cells["addCustomDomainCell"])
app.tables.cells["addCustomDomainCell"].tap()
// Edit Text Field
let urlInput = app.textFields["urlInput"]
urlInput.tap()
urlInput.typeText("mozilla.org")
waitforHittable(element: app.navigationBars.buttons["saveButton"])
app.navigationBars.buttons["saveButton"].tap()
// Validate that the new domain shows up in the Autocomplete Settings
waitforExistence(element: app.tables.cells["mozilla.org"])
// Start Editing
waitforHittable(element: app.navigationBars.buttons["editButton"])
app.navigationBars.buttons["editButton"].tap()
waitforHittable(element: app.tables.cells["mozilla.org"].buttons["Delete mozilla.org"])
app.tables.cells["mozilla.org"].buttons["Delete mozilla.org"].tap()
waitforHittable(element: app.tables.cells["mozilla.org"].buttons["Delete"])
app.tables.cells["mozilla.org"].buttons["Delete"].tap()
// Finish Editing
waitforHittable(element: app.navigationBars.buttons["editButton"])
app.navigationBars.buttons["editButton"].tap()
// Validate that the domain is gone
XCTAssertFalse(app.tables.cells["mozilla.org"].exists)
}
}
|
mpl-2.0
|
2b06f2b42717906275807e1f466faab4
| 39.329949 | 109 | 0.666834 | 4.726353 | false | false | false | false |
craiggrummitt/ActionSwift3
|
ActionSwift3/media/Sound.swift
|
1
|
1345
|
//
// Sound.swift
// ActionSwift
//
// Created by Craig on 6/08/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import SpriteKit
/**
Be sure to store either the sound or soundChannel in an instance variable, as the sound will be "garbage collected"
(or the Swift equivalent at least, *deinitialized* when there are no references to it)
*/
open class Sound: EventDispatcher {
fileprivate var name:String
fileprivate var soundChannel:SoundChannel = SoundChannel()
public init(name:String) {
self.name = name
}
open func load(_ name:String) {
self.name = name
}
/**
Generates a new SoundChannel object to play back the sound. This method returns a SoundChannel object, which you access to stop the sound.
- Parameters:
- startTime: The initial position in milliseconds at which playback should start.
- loops: Defines the number of times a sound loops back to the startTime value before the sound channel stops playback.
- Returns: a SoundChannel, which you can use to *stop* the Sound.
*/
@discardableResult open func play(_ startTime:Number = 0, loops:int = 0)->SoundChannel {
soundChannel = SoundChannel()
soundChannel.play(self.name,startTime:startTime, loops:loops)
return soundChannel
}
}
|
mit
|
b6d2e34df63234f0aa32b7c95ebd99b6
| 34.394737 | 143 | 0.692937 | 4.33871 | false | false | false | false |
LukaszLiberda/Swift-Design-Patterns
|
PatternProj/Structural/CompositePattern.swift
|
1
|
3652
|
//
// CompositePattern.swift
// PatternProj
//
// Created by lukaszliberda on 06.07.2015.
// Copyright (c) 2015 lukasz. All rights reserved.
//
import Foundation
/*
The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.[1]
*/
protocol Shape {
func draw(fillColor: String)
}
// Leafs
class Square: Shape {
func draw(fillColor: String) {
println("Drawing a Square with color \(fillColor)")
}
}
class Circle: Shape {
func draw(fillColor: String) {
println("Drawing a circle with color \(fillColor)")
}
}
// Composite
class Whiteboard: Shape {
lazy var shapes = [Shape]()
init(_ shapes: Shape...) {
self.shapes = shapes
}
func draw(fillColor: String) {
for shape in self.shapes {
shape.draw(fillColor)
}
}
}
/*
usage
*/
class TestComposite {
func test() {
var whiteboard = Whiteboard(Circle(), Square())
whiteboard.draw("Red")
println()
}
func test2() {
var root: Composite = Composite(name: "root")
root.add(Leaf(name: "Leaf A"))
root.add(Leaf(name: "Leaf B"))
var comp: Composite = Composite(name: "Composite X")
comp.add(Leaf(name: "Leaf XA"))
comp.add(Leaf(name: "Leaf XB"))
root.add(comp)
root.add(Leaf(name: "Leaf C"))
var leaf: Leaf = Leaf(name: "Leaf D")
root.add(leaf)
root.remove(leaf)
root.display(1)
println()
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Component {
var name: String
init(name:String) {
self.name = name
}
func add(c: Component) {}
func remove(c: Component) {}
func display(depth:Int) {}
}
class Composite: Component {
var children: [Component] = []
override init(name: String) {
super.init(name: name)
}
override func add(c: Component) {
children.append(c)
}
override func remove(c: Component) {
var index = 0
for elm in self.children {
if elm.name == c.name {
self.children.removeAtIndex(index)
return
}
index++
}
}
override func display(depth: Int) {
var str = "-".repeatString(depth)
println("\(str) \(depth) + \(name)")
for c in children {
c.display(depth + 2)
}
}
}
class Leaf: Component {
override init(name:String) {
super.init(name: name)
}
override func add(c: Component) {
println("Cannot add to leaf")
}
override func remove(c: Component) {
println("Cannot remove from leaf")
}
override func display(depth: Int) {
var str = "-".repeatString(depth)
println("\(str) \(depth) + \(name)")
}
}
extension String {
func repeatString(n: Int) -> String {
return "".join(Array(count: n, repeatedValue: self))
}
}
|
gpl-2.0
|
9fd732511d296411703a926e038f4fae
| 20.482353 | 416 | 0.561336 | 4.173714 | false | false | false | false |
material-components/material-components-ios
|
components/AppBar/examples/AppBarCustomButtonThemeExample.swift
|
2
|
4576
|
// Copyright 2020-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialAppBar_Theming
import MaterialComponents.MaterialButtons_Theming
import MaterialComponents.MaterialContainerScheme
class AppBarCustomButtonThemeExample: UITableViewController {
let appBarViewController = MDCAppBarViewController()
@objc var containerScheme: MDCContainerScheming = MDCContainerScheme()
deinit {
// Required for pre-iOS 11 devices because we've enabled observesTrackingScrollViewScrollEvents.
appBarViewController.headerView.trackingScrollView = nil
}
init() {
super.init(nibName: nil, bundle: nil)
self.title = "Custom button theme"
// Behavioral flags.
appBarViewController.inferTopSafeAreaInsetFromViewController = true
appBarViewController.headerView.minMaxHeightIncludesSafeArea = false
// Step 2: Add the headerViewController as a child.
self.addChild(appBarViewController)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
appBarViewController.headerView.observesTrackingScrollViewScrollEvents = true
appBarViewController.headerView.trackingScrollView = self.tableView
view.addSubview(appBarViewController.view)
appBarViewController.didMove(toParent: self)
appBarViewController.applySurfaceTheme(withScheme: containerScheme)
// To create a custom-themed button we create a custom button placed inside a container which
// will be set as a custom view on the navigationItem.
let containerView = UIView()
let button = MDCButton()
button.applyContainedTheme(withScheme: containerScheme)
button.setTitle("Right", for: .normal)
button.sizeToFit()
// Give the button horizontal insets so that it's not flush with the device's edge.
containerView.frame = CGRect(
x: 0,
y: 8,
width: button.bounds.width + 16,
height: button.bounds.height)
// Vertically center the button:
button.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
containerView.addSubview(button)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: containerView)
}
// Optional step: If you allow the header view to hide the status bar you must implement this
// method and return the headerViewController.
override var childForStatusBarHidden: UIViewController? {
return appBarViewController
}
// Optional step: The Header View Controller does basic inspection of the header view's background
// color to identify whether the status bar should be light or dark-themed.
override var childForStatusBarStyle: UIViewController? {
return appBarViewController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
}
// MARK: Catalog by convention
extension AppBarCustomButtonThemeExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["App Bar", "Custom button theme"],
"primaryDemo": false,
"presentable": false,
]
}
@objc func catalogShouldHideNavigation() -> Bool {
return true
}
}
// MARK: - Typical application code (not Material-specific)
// MARK: UITableViewDataSource
extension AppBarCustomButtonThemeExample {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell =
self.tableView.dequeueReusableCell(withIdentifier: "cell")
?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.layoutMargins = .zero
cell.textLabel?.text = "\(indexPath.row)"
cell.selectionStyle = .none
return cell
}
}
|
apache-2.0
|
ef5a401a06b9f8aa5c93966b50231b8e
| 32.896296 | 100 | 0.744318 | 5.006565 | false | false | false | false |
nfls/nflsers
|
app/v2/Controller/Media/GalleryListController.swift
|
1
|
2512
|
//
// GalleryListController.swift
// NFLSers-iOS
//
// Created by Qingyang Hu on 21/01/2018.
// Copyright © 2018 胡清阳. All rights reserved.
//
import Foundation
import SDWebImage
import AVFoundation
class AlbumCell: UITableViewCell {
@IBOutlet weak var cover: ScaledHeightImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var subtitle: UILabel!
final func setImage(image: UIImage) {
cover?.image = image
cover?.frame = AVMakeRect(aspectRatio: image.size, insideRect: cover.frame)
self.layoutIfNeeded()
}
}
class GalleryListController: UITableViewController {
let provider = GalleryProvider()
override func viewDidLoad() {
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 200
provider.getList {
self.tableView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.navigationItem.rightBarButtonItem = nil
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return provider.list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AlbumCell
SDWebImageManager.shared().loadImage(with: provider.list[indexPath.row].cover?.hdUrl, options: SDWebImageOptions.highPriority, progress: nil) { (image, _, _, _, _, _) in
DispatchQueue.main.async {
cell.setImage(image: image!)
}
}
cell.title!.text = provider.list[indexPath.row].title
let description = provider.list[indexPath.row].description
if description != "" {
cell.subtitle!.text = provider.list[indexPath.row].description
} else {
cell.subtitle!.isHidden = true
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.provider.getDetail(id: provider.list[indexPath.row].id) {
self.performSegue(withIdentifier: "showDetail", sender: self.provider.detail)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let viewController = segue.destination as! GalleryDetailController
viewController.gallery = (sender as! Gallery)
}
}
|
apache-2.0
|
88d687823abab32920a5dd84591b70a6
| 34.28169 | 177 | 0.663872 | 4.921415 | false | false | false | false |
Insfgg99x/XGFDownloader
|
Classes/XGFDownloader.swift
|
1
|
8867
|
//
// XGFDownloader.swift
// XGFDownloader
//
// Created by 夏桂峰 on 16/6/6.
// Copyright © 2016年 夏桂峰. All rights reserved.
//
import Foundation
import UIKit
/**
* 下载完成的通知名
*/
let FGGDownloadTaskDidFinishDownloadingNotification="FGGDownloadTaskDidFinishDownloadingNotification";
/// 内存空间不足的通知名
let FGGDownloaderInsufficientSystemFreeSpaceNotification="FGGDownloaderInsufficientSystemFreeSpaceNotification"
/// 下载过程中回调的代码块,会多次调用
typealias ProcessHandle=(_ progress:Float,_ sizeString:String?,_ speedString:String?)->Void
/// 下载完成的回调
typealias CompletionHandle=()->Void
/// 下载失败的回调
typealias FailureHandle=(_ error:Error)->Void
class XGFDownloader: NSObject,NSURLConnectionDataDelegate,NSURLConnectionDelegate{
var process:ProcessHandle?
var completion:CompletionHandle?
var failure:FailureHandle?
var growthSize:NSInteger?
var lastSize:NSInteger?
var destination_path:String?
var urlString:String?
var con:NSURLConnection?
var writeHandle:FileHandle?
private var timer:Timer?
override init() {
super.init()
self.growthSize=0
self.lastSize=0
self.timer=Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(XGFDownloader.getGrowthSize), userInfo: nil, repeats: true)
}
//与计算网速相关的方法
@objc func getGrowthSize() {
do{
let dict:Dictionary=try FileManager.default.attributesOfItem(atPath: self.destination_path!)
let size=dict[.size] as! NSInteger
self.growthSize=size-self.lastSize!
self.lastSize=size
}
catch {
}
}
//MARK:断点下载
func download(urlString:String?,toPath:String?,process:ProcessHandle?,completion:CompletionHandle?,failure:FailureHandle?){
if (toPath == nil) || (urlString==nil){
return;
}
self.destination_path=toPath
self.urlString=urlString
self.process=process
self.completion=completion
self.failure=failure
let url=URL(string:urlString!)
let request=NSMutableURLRequest(url: url!)
let exist=FileManager.default.fileExists(atPath: toPath!)
if exist {
do {
let dict:Dictionary=try FileManager.default.attributesOfItem(atPath: toPath!)
let length:NSInteger=dict[.size] as! NSInteger
let rangeString=String.init(format: "bytes=%ld-", length)
request.setValue(rangeString, forHTTPHeaderField: "Range")
}
catch {
}
}
self.con=NSURLConnection(request: request as URLRequest, delegate: self)
}
//MARK:便捷方法
class func downloader() -> XGFDownloader {
let downloader=XGFDownloader();
return downloader;
}
class func lastProgress(url:String?)->Float{
if(url==nil){
return 0.0;
}
return UserDefaults.standard.float(forKey: String(format: "%@progress",url!))
}
//MARK:Cancel
func cancel(){
self.con?.cancel()
self.con=nil
if (self.timer != nil){
self.timer?.invalidate()
self.timer=nil
}
}
class func filesSize(url:String?)->String{
if(url==nil){
return "0.00K/0.00K"
}
let lenthKey=String(format: "%@totalLength",url!)
let totalLength=UserDefaults.standard.integer(forKey: lenthKey)
if(totalLength==0){
return "0.00K/0.00K"
}
let progressKey=String(format: "%@progress",url!)
let downloadProgress=UserDefaults.standard.float(forKey: progressKey)
let currentLength=Int(Float(totalLength) * downloadProgress)
let currentSize=self.convertSize(length: currentLength)
let totalSize=self.convertSize(length: totalLength)
return String(format: "%@/%@",currentSize,totalSize)
}
//MARK:转换
class func convertSize(length:NSInteger?)->String{
if length!<1024 {
return String(format: "%ldB",length!)
}
else if length!>=1024&&length!<1024*1024 {
return String(format: "%.0fK",Float(length!/1024))
}
else if length!>=1024*1024&&length!<1024*1024*1024 {
return String(format: "%.1fM",Float(length!)/(1024.0*1024.0))
}
else{
return String(format: "%.1fG",Float(length!/(1024*1024*1024)))
}
}
//MARK:NSURLConnection
func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
if (self.failure != nil){
self.failure!(error)
}
}
func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
let lenthKey=String(format: "%@totalLength",self.urlString!)
let totalLength=UserDefaults.standard.integer(forKey: lenthKey)
if(totalLength==0){
let expectLength=Int(response.expectedContentLength);
UserDefaults.standard.set(expectLength, forKey: lenthKey)
UserDefaults.standard.synchronize()
}
let exist=FileManager.default.fileExists(atPath: self.destination_path!)
if !exist{
FileManager.default.createFile(atPath: self.destination_path!, contents: nil, attributes: nil)
}
self.writeHandle=FileHandle.init(forWritingAtPath: self.destination_path!)
//print(self.destination_path)
}
func connection(_ connection: NSURLConnection, didReceive data: Data) {
self.writeHandle?.seekToEndOfFile()
let systemFreeSpace=self.systemAvailableSpace()
if(systemFreeSpace<1024*1024*20){
let alert:UIAlertController=UIAlertController.init(title: "提示", message: "可用存储空间不足20M", preferredStyle: UIAlertControllerStyle.alert)
let confirmAction=UIAlertAction.init(title: "确定", style: UIAlertActionStyle.default, handler: nil)
alert.addAction(confirmAction)
let root=UIApplication.shared.keyWindow?.rootViewController
root?.present(alert, animated: true, completion: nil)
//发送系统存储空间不足的通知
let dict:Dictionary<String,String>=["urlString":self.urlString!]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: FGGDownloaderInsufficientSystemFreeSpaceNotification), object: nil, userInfo: dict)
return
}
self.writeHandle?.write(data)
do{
let dict:Dictionary=try FileManager.default.attributesOfItem(atPath: self.destination_path!)
let length:NSInteger?=dict[.size] as? NSInteger
let lenthKey=String(format: "%@totalLength",self.urlString!)
let totalLength=UserDefaults.standard.integer(forKey: lenthKey)
let downloadProgress=Float(length!)/(Float(totalLength))
let progressKey=String(format: "%@progress",self.urlString!)
UserDefaults.standard.set(downloadProgress, forKey: progressKey)
UserDefaults.standard.synchronize()
let sizeString=XGFDownloader.filesSize(url: self.urlString)
//print(sizeString)
var speedString="0.0Kb/s"
let growthString=XGFDownloader.convertSize(length: self.growthSize!*Int(1.0/0.1))
speedString=String(format: "%@/s",growthString)
//print(speedString)
if self.process != nil {
self.process!(downloadProgress,sizeString,speedString)
}
}
catch {
}
}
func connectionDidFinishLoading(_ connection: NSURLConnection) {
let dict:Dictionary<String,String>=["urlString":self.urlString!]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: FGGDownloadTaskDidFinishDownloadingNotification), object: nil,userInfo:dict)
self.cancel()
if self.completion != nil {
self.completion!()
}
}
//MARK:获取系统可用存储空间
func systemAvailableSpace()->NSInteger{
var freeSpace:NSInteger=0
let docPath=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
do {
let dict:Dictionary<FileAttributeKey,Any>=try FileManager.default.attributesOfFileSystem(forPath: docPath!)
freeSpace=dict[.systemFreeSize] as! NSInteger;
}
catch {
}
return freeSpace
}
}
|
mit
|
e78c2d7fa5f36eb04f0726b2124c5354
| 34.42623 | 163 | 0.624942 | 4.617521 | false | false | false | false |
developerY/Swift2_Playgrounds
|
Swift Standard Library.playground/Sources/RecipeApp.swift
|
1
|
5355
|
import UIKit
public struct Ingredient: Equatable {
public let name: String
public let quantity: Int
public let price: Int
public let purchased: Bool
public init(name: String, quantity: Int, price: Int, purchased: Bool) {
self.name = name
self.quantity = quantity
self.price = price
self.purchased = purchased
}
public var dictionaryRepresentation: [String: AnyObject] {
get {
return [
"name": name,
"quantity": quantity,
"price": price,
"purchased": purchased
]
}
}
}
public func == (lhs: Ingredient, rhs: Ingredient) -> Bool {
return lhs.name == rhs.name && lhs.price == rhs.price && lhs.purchased == rhs.purchased
}
public let sampleIngredients: [Ingredient] = [
Ingredient(name: "Tomato", quantity: 1, price: 2, purchased: false),
Ingredient(name: "Saffron", quantity: 1, price: 6, purchased: false),
Ingredient(name: "Chicken", quantity: 2, price: 3, purchased: true),
Ingredient(name: "Rice", quantity: 1, price: 2, purchased: false),
Ingredient(name: "Onion", quantity: 2, price: 1, purchased: true),
Ingredient(name: "Garlic", quantity: 4, price: 1, purchased: false),
Ingredient(name: "Pepper", quantity: 2, price: 3, purchased: false),
Ingredient(name: "Salt", quantity: 1, price: 1, purchased: false)
]
@available(iOS 9.0, *)
class MapCell: UITableViewCell {
let leftTextLabel = UILabel()
let middleTextLabel = UILabel()
let rightTextLabel = UILabel()
let stack = UIStackView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
middleTextLabel.text = "→"
middleTextLabel.textAlignment = .Center
middleTextLabel.font = UIFont.boldSystemFontOfSize(20)
rightTextLabel.textAlignment = .Right
stack.distribution = UIStackViewDistribution.FillEqually
stack.frame = self.contentView.bounds
stack.addArrangedSubview(leftTextLabel)
stack.addArrangedSubview(middleTextLabel)
stack.addArrangedSubview(rightTextLabel)
self.contentView.addSubview(stack)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
stack.frame = self.contentView.bounds
}
}
private let IngredientCellIdentifier = "IngredientCellIdentifier"
private class IngredientsListViewController: UITableViewController {
var ingredients: [Ingredient]
var filteredList: [Ingredient]?
var transformed: [Int]?
init(list: [Ingredient]) {
ingredients = list
super.init(style: .Plain)
self.view.frame = CGRect(x: 0, y: 0, width: 300, height: list.count * 44)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: IngredientCellIdentifier)
self.tableView.registerClass(MapCell.self, forCellReuseIdentifier: "MapCell")
self.tableView.separatorStyle = .SingleLine
self.tableView.separatorColor = .blueColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ingredients.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = transformed == nil ? IngredientCellIdentifier : "MapCell"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
let ingredient = ingredients[indexPath.row]
if let transforms = transformed {
let mapCell = cell as! MapCell
mapCell.leftTextLabel.text = "\(ingredient.quantity)x " + ingredient.name
let transformedValue = transforms[indexPath.row]
mapCell.rightTextLabel.text = "$\(transformedValue)"
} else {
cell.textLabel!.text = "\(ingredient.quantity)x " + ingredient.name
cell.accessoryType = ingredient.purchased ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
if filteredList != nil {
cell.tintColor = UIColor.whiteColor()
}
let keep = filteredList?.contains(ingredient) ?? true
cell.textLabel!.textColor = keep ? UIColor.blackColor() : UIColor.whiteColor()
cell.backgroundColor = keep ? UIColor.whiteColor() : UIColor(red: 126/255.0, green: 72/255.0, blue: 229/255.0, alpha: 1.0)
}
return cell
}
}
public func showIngredients(list: [Ingredient]) -> UIView {
return IngredientsListViewController(list: list).view
}
public func visualize(list: [Ingredient], _ filteredList: [Ingredient]) -> UIView {
let list = IngredientsListViewController(list: list)
list.filteredList = filteredList
return list.view
}
public func visualize(list: [Ingredient], _ transformed: [Int]) -> UIView {
let list = IngredientsListViewController(list: list)
list.transformed = transformed
return list.view
}
|
mit
|
b6f917643c8cbfca557361b85b214675
| 36.433566 | 134 | 0.660751 | 4.712148 | false | false | false | false |
oguntli/swift-grant-o-meter
|
Sources/libgrumpy/Utilities/Validators.swift
|
2
|
971
|
//
// Copyright 2017 Oliver Guntli
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
//
import Vapor
import Foundation
/// Password validator checks if a password matches these criteria:
/// * At least 8 characters long
/// * At least 1 uppercase letter
/// * At least 1 number
public struct PasswordValidator: ValidationSuite {
public static func validate(input value: String) throws {
guard value.characters.count >= 8 else {
throw error(with: value, message: "The password must be at least 8 characters long")
}
let range = value.range(of: "^(?=.*[0-9])(?=.*[A-Z])", options: .regularExpression)
guard let _ = range else {
throw error(with: value, message: "the password must at least contain a number and an upper case letter")
}
}
}
|
mpl-2.0
|
4d27695ce9b181e272ec1ed657b990fb
| 34.962963 | 117 | 0.661174 | 4.012397 | false | false | false | false |
CosmicMind/MaterialKit
|
Sources/iOS/CardCollectionViewController.swift
|
1
|
3954
|
/*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
extension UIViewController {
/**
A convenience property that provides access to the CardCollectionViewController.
This is the recommended method of accessing the CardCollectionViewController
through child UIViewControllers.
*/
public var cardCollectionViewController: CardCollectionViewController? {
return traverseViewControllerHierarchyForClassType()
}
}
open class CardCollectionViewController: ViewController {
/// A reference to a Reminder.
open let collectionView = CollectionView()
open var dataSourceItems = [DataSourceItem]()
/// An index of IndexPath to DataSourceItem.
open var dataSourceItemsIndexPaths = [IndexPath: Any]()
open override func prepare() {
super.prepare()
prepareCollectionView()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutCollectionView()
}
}
extension CardCollectionViewController {
/// Prepares the collectionView.
fileprivate func prepareCollectionView() {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(CardCollectionViewCell.self, forCellWithReuseIdentifier: "CardCollectionViewCell")
view.addSubview(collectionView)
layoutCollectionView()
}
}
extension CardCollectionViewController {
/// Sets the frame for the collectionView.
fileprivate func layoutCollectionView() {
collectionView.frame = view.bounds
}
}
extension CardCollectionViewController: CollectionViewDelegate {}
extension CardCollectionViewController: CollectionViewDataSource {
@objc
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
@objc
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSourceItems.count
}
@objc
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCollectionViewCell", for: indexPath) as! CardCollectionViewCell
guard let card = dataSourceItems[indexPath.item].data as? Card else {
return cell
}
dataSourceItemsIndexPaths[indexPath] = card
card.frame = cell.bounds
cell.card = card
return cell
}
}
|
bsd-3-clause
|
65c22b2da3d0113b7000dfd60482828a
| 34.303571 | 139 | 0.75999 | 5.182176 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/Services/HomepageSettingsService.swift
|
2
|
2950
|
import Foundation
import WordPressKit
/// Service allowing updating of homepage settings
///
struct HomepageSettingsService {
public enum ResponseError: Error {
case decodingFailed
}
let blog: Blog
fileprivate let context: NSManagedObjectContext
fileprivate let remote: HomepageSettingsServiceRemote
fileprivate let siteID: Int
init?(blog: Blog, context: NSManagedObjectContext) {
guard let api = blog.wordPressComRestApi(), let dotComID = blog.dotComID as? Int else {
return nil
}
self.remote = HomepageSettingsServiceRemote(wordPressComRestApi: api)
self.siteID = dotComID
self.blog = blog
self.context = context
}
public func setHomepageType(_ type: HomepageType,
withPostsPageID postsPageID: Int? = nil,
homePageID: Int? = nil,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
// Keep track of the original settings in case we need to revert
let originalHomepageType = blog.homepageType
let originalHomePageID = blog.homepagePageID
let originalPostsPageID = blog.homepagePostsPageID
switch type {
case .page:
blog.homepageType = .page
if let postsPageID = postsPageID {
blog.homepagePostsPageID = postsPageID
if postsPageID == originalHomePageID {
// Don't allow the same page to be set for both values
blog.homepagePageID = 0
}
}
if let homePageID = homePageID {
blog.homepagePageID = homePageID
if homePageID == originalPostsPageID {
// Don't allow the same page to be set for both values
blog.homepagePostsPageID = 0
}
}
case .posts:
blog.homepageType = .posts
}
ContextManager.sharedInstance().save(context)
remote.setHomepageType(type: type.remoteType,
for: siteID,
withPostsPageID: blog.homepagePostsPageID,
homePageID: blog.homepagePageID,
success: success,
failure: { error in
self.context.performAndWait {
self.blog.homepageType = originalHomepageType
self.blog.homepagePostsPageID = originalPostsPageID
self.blog.homepagePageID = originalHomePageID
ContextManager.sharedInstance().saveContextAndWait(self.context)
}
failure(error)
})
}
}
|
gpl-2.0
|
6f1962abc123e445b901ade25f800e70
| 36.820513 | 100 | 0.533559 | 6.020408 | false | false | false | false |
ktmswzw/FeelingClientBySwift
|
Pods/Whisper/Source/Message.swift
|
1
|
1464
|
import UIKit
public struct Message {
public var title: String
public var textColor: UIColor
public var backgroundColor: UIColor
public var images: [UIImage]?
public init(title: String, textColor: UIColor = UIColor.whiteColor(), backgroundColor: UIColor = UIColor.lightGrayColor(), images: [UIImage]? = nil) {
self.title = title
self.textColor = textColor
self.backgroundColor = backgroundColor
self.images = images
}
}
public struct Announcement {
public var title: String
public var subtitle: String?
public var image: UIImage?
public var duration: NSTimeInterval
public var action: (() -> Void)?
public init(title: String, subtitle: String? = nil, image: UIImage? = nil, duration: NSTimeInterval = 2, action: (() -> Void)? = nil) {
self.title = title
self.subtitle = subtitle
self.image = image
self.duration = duration
self.action = action
}
}
public struct Murmur {
public var title: String
public var duration: NSTimeInterval
public var backgroundColor: UIColor
public var titleColor: UIColor
public var font: UIFont
public init(title: String, duration: NSTimeInterval = 1.5, backgroundColor: UIColor = ColorList.Whistle.background, titleColor: UIColor = ColorList.Whistle.title, font: UIFont = FontList.Whistle.title) {
self.title = title
self.duration = duration
self.backgroundColor = backgroundColor
self.titleColor = titleColor
self.font = font
}
}
|
mit
|
5fbeb4335e1f3af29f73362b043294be
| 28.28 | 205 | 0.715847 | 4.449848 | false | false | false | false |
zzgo/v2ex
|
v2ex/Pods/PKHUD/PKHUD/PKHUD.swift
|
8
|
6128
|
//
// HUD.swift
// PKHUD
//
// Created by Philip Kluz on 6/13/14.
// Copyright (c) 2016 NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import UIKit
/// The PKHUD object controls showing and hiding of the HUD, as well as its contents and touch response behavior.
open class PKHUD: NSObject {
fileprivate struct Constants {
static let sharedHUD = PKHUD()
}
public var viewToPresentOn: UIView? = nil
fileprivate let container = ContainerView()
fileprivate var hideTimer: Timer?
public typealias TimerAction = (Bool) -> Void
fileprivate var timerActions = [String: TimerAction]()
/// Grace period is the time (in seconds) that the invoked method may be run without
/// showing the HUD. If the task finishes before the grace time runs out, the HUD will
/// not be shown at all.
/// This may be used to prevent HUD display for very short tasks.
/// Defaults to 0 (no grace time).
public var graceTime: TimeInterval = 0
fileprivate var graceTimer: Timer?
// MARK: Public
open class var sharedHUD: PKHUD {
return Constants.sharedHUD
}
public override init () {
super.init()
NotificationCenter.default.addObserver(self,
selector: #selector(PKHUD.willEnterForeground(_:)),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
userInteractionOnUnderlyingViewsEnabled = false
container.frameView.autoresizingMask = [ .flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleBottomMargin ]
self.container.isAccessibilityElement = true
self.container.accessibilityIdentifier = "PKHUD"
}
public convenience init(viewToPresentOn view: UIView) {
self.init()
viewToPresentOn = view
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open var dimsBackground = true
open var userInteractionOnUnderlyingViewsEnabled: Bool {
get {
return !container.isUserInteractionEnabled
}
set {
container.isUserInteractionEnabled = !newValue
}
}
open var isVisible: Bool {
return !container.isHidden
}
open var contentView: UIView {
get {
return container.frameView.content
}
set {
container.frameView.content = newValue
startAnimatingContentView()
}
}
open var effect: UIVisualEffect? {
get {
return container.frameView.effect
}
set {
container.frameView.effect = newValue
}
}
open func show(onView view: UIView? = nil) {
let view: UIView = view ?? viewToPresentOn ?? UIApplication.shared.keyWindow!
if !view.subviews.contains(container) {
view.addSubview(container)
container.frame.origin = CGPoint.zero
container.frame.size = view.frame.size
container.autoresizingMask = [ .flexibleHeight, .flexibleWidth ]
container.isHidden = true
}
if dimsBackground {
container.showBackground(animated: true)
}
// If the grace time is set, postpone the HUD display
if graceTime > 0.0 {
let timer = Timer(timeInterval: graceTime, target: self, selector: #selector(PKHUD.handleGraceTimer(_:)), userInfo: nil, repeats: false)
RunLoop.current.add(timer, forMode: .commonModes)
graceTimer = timer
} else {
showContent()
}
}
func showContent() {
graceTimer?.invalidate()
container.showFrameView()
startAnimatingContentView()
}
open func hide(animated anim: Bool = true, completion: TimerAction? = nil) {
graceTimer?.invalidate()
container.hideFrameView(animated: anim, completion: completion)
stopAnimatingContentView()
}
open func hide(_ animated: Bool, completion: TimerAction? = nil) {
hide(animated: animated, completion: completion)
}
open func hide(afterDelay delay: TimeInterval, completion: TimerAction? = nil) {
let key = UUID().uuidString
let userInfo = ["timerActionKey": key]
if let completion = completion {
timerActions[key] = completion
}
hideTimer?.invalidate()
hideTimer = Timer.scheduledTimer(timeInterval: delay,
target: self,
selector: #selector(PKHUD.performDelayedHide(_:)),
userInfo: userInfo,
repeats: false)
}
// MARK: Internal
internal func willEnterForeground(_ notification: Notification?) {
self.startAnimatingContentView()
}
internal func startAnimatingContentView() {
if let animatingContentView = contentView as? PKHUDAnimating, isVisible {
animatingContentView.startAnimation()
}
}
internal func stopAnimatingContentView() {
if let animatingContentView = contentView as? PKHUDAnimating {
animatingContentView.stopAnimation?()
}
}
// MARK: Timer callbacks
internal func performDelayedHide(_ timer: Timer? = nil) {
let userInfo = timer?.userInfo as? [String:AnyObject]
let key = userInfo?["timerActionKey"] as? String
var completion: TimerAction?
if let key = key, let action = timerActions[key] {
completion = action
timerActions[key] = nil
}
hide(animated: true, completion: completion)
}
internal func handleGraceTimer(_ timer: Timer? = nil) {
// Show the HUD only if the task is still running
if (graceTimer?.isValid)! {
showContent()
}
}
}
|
mit
|
af4c4b5fd8948feb20f174e2ccfc45ec
| 30.751295 | 148 | 0.593832 | 5.291883 | false | false | false | false |
ifabijanovic/cash-splash-ios-swift
|
CashSplash/CashSplash/Data/Dropbox/CSDropboxSpendingStorer.swift
|
1
|
5163
|
//
// CSDropboxSpendingStorer.swift
// CashSplash
//
// Created by Ivan Fabijanovic on 06/10/14.
// Copyright (c) 2014 Ivan Fabijanovic. All rights reserved.
//
import UIKit
internal class CSDropboxSpendingStorer<T: Equatable>: CSSpendingStorer<CSSpending> {
// MARK: - Properties
private let tableName = "spending_model"
private let datastore : DBDatastore?
private let table : DBTable?
// MARK: - Init
internal init(datastore: DBDatastore?) {
self.datastore = datastore
if (datastore != nil) {
self.table = self.datastore!.getTable(self.tableName)
}
}
// MARK: - Public methods
internal override func getAll() -> Array<CSSpending> {
if (self.table != nil) {
CSDropboxManager.syncDatastore(self.datastore)
var error : DBError? = nil
let data : NSArray! = self.table!.query(nil, error: &error)
if (error != nil) {
NSLog("[Dropbox] Spending getAll error: %@", error!)
return Array<CSSpending>()
}
let dataArray = data as Array<DBRecord>
var items = Array<CSSpending>()
for item in dataArray {
items.append(self.spendingFromDBRecord(item))
}
return items
}
return Array<CSSpending>()
}
internal override func getAllFromDate(date: NSDate) -> Array<CSSpending> {
var items = self.getAll()
sort(&items, {
let result = $0.timestamp.compare($1.timestamp)
return result == NSComparisonResult.OrderedDescending
})
return items
}
internal override func get(key: String) -> CSSpending? {
if (self.table != nil) {
CSDropboxManager.syncDatastore(self.datastore)
var error : DBError? = nil
let dictionary = ["key": key] as NSDictionary
let records : NSArray! = self.table!.query(dictionary, error: &error)
if (error != nil) {
NSLog("[Dropbox] Spending get error: %@", error!)
return nil
}
error = nil
let data = records as Array<DBRecord>
let record : DBRecord? = data.isEmpty ? nil : data[0]
if (record != nil) {
return self.spendingFromDBRecord(record!)
}
}
return nil
}
internal override func save(item: CSSpending) -> Bool {
if (self.table != nil) {
var error : DBError? = nil
let item = self.dictionaryFromSpending(item)
self.table!.insert(item)
self.datastore!.sync(&error)
if (error != nil) {
NSLog("[Dropbox] Spending save error: %@", error!);
return false
}
return true
}
return false
}
internal override func remove(item: CSSpending) -> Bool {
if (self.table != nil) {
var error : DBError? = nil
let dictionary = ["key": item.key] as NSDictionary
let records : NSArray! = self.table!.query(dictionary, error: &error)
if (error != nil) {
NSLog("[Dropbox] Spending remove error: %@", error!);
return false
}
error = nil
let data = records as Array<DBRecord>
let record : DBRecord? = data.isEmpty ? nil : data[0]
if (record != nil) {
record!.deleteRecord()
self.datastore!.sync(&error)
if (error != nil) {
NSLog("[Dropbox] Spending remove error: %@", error!);
return false
}
}
return true
}
return false
}
// MARK: - Private methods
private func spendingFromDBRecord(dbRecord: DBRecord) -> CSSpending {
var spending = CSSpending(key: dbRecord["key"] as String)
spending.amount = dbRecord["amount"] as Float
spending.category = dbRecord["category"] as String?
spending.label = dbRecord["label"] as String?
spending.timestamp = dbRecord["timestamp"] as NSDate
spending.note = dbRecord["note"] as String?
return spending
}
private func dictionaryFromSpending(spending : CSSpending) -> NSDictionary {
var dictionary = NSDictionary()
dictionary.setValue(spending.key, forKey: "key")
dictionary.setValue(NSNumber(float: spending.amount), forKey: "amount")
dictionary.setValue(spending.category, forKey: "category")
dictionary.setValue(spending.label, forKey: "label")
dictionary.setValue(spending.timestamp, forKey: "timestamp")
dictionary.setValue(spending.note, forKey: "note")
return dictionary
}
}
|
mit
|
36a71495cdc72fe06ecc40c1143f5abb
| 30.481707 | 84 | 0.52392 | 4.719378 | false | false | false | false |
CulturaMobile/culturamobile-api
|
Sources/App/Models/EventCategory.swift
|
1
|
2260
|
import Vapor
import FluentProvider
import AuthProvider
import HTTP
final class EventCategory: Model {
fileprivate static let databaseTableName = "event_categories"
static var entity = "event_categories"
let storage = Storage()
static let idKey = "id"
static let foreignIdKey = "event_categories_id"
var event: Identifier?
var category: Identifier?
init(event: Event, category: Category) {
self.event = event.id
self.category = category.id
}
// MARK: Row
/// Initializes from the database row
init(row: Row) throws {
event = try row.get("event_id")
category = try row.get("category_id")
}
// Serializes object to the database
func makeRow() throws -> Row {
var row = Row()
try row.set("event_id", event)
try row.set("category_id", category)
return row
}
}
// MARK: Preparation
extension EventCategory: Preparation {
/// Prepares a table/collection in the database for storing objects
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.int("event_id")
builder.int("category_id")
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSON
// How the model converts from / to JSON.
//
extension EventCategory: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
event: json.get("event_id"),
category: json.get("category_id")
)
id = try json.get("id")
}
func makeJSON() throws -> JSON {
var json = JSON()
let currentCategories = try Category.makeQuery().filter("id", category).all()
for c in currentCategories {
try json.set("name", c.name)
}
return json
}
}
extension EventCategory: ResponseRepresentable { }
extension EventCategory: Timestampable {
static var updatedAtKey: String { return "updated_at" }
static var createdAtKey: String { return "created_at" }
}
|
mit
|
4d6e182b256a70095d5343131ff200e2
| 24.111111 | 85 | 0.593805 | 4.493042 | false | false | false | false |
tribalworldwidelondon/CassowarySwift
|
Sources/Cassowary/Symbol.swift
|
1
|
2257
|
/*
Copyright (c) 2017, Tribal Worldwide London
Copyright (c) 2015, Alex Birkett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of kiwi-java nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public final class Symbol {
public enum SymbolType {
case invalid
case external
case slack
case error
case dummy
}
private(set) var symbolType: SymbolType
public init() {
symbolType = .invalid
}
public init(_ symbolType: SymbolType) {
self.symbolType = symbolType
}
}
// MARK: Equatable
extension Symbol: Equatable {
public static func == (lhs: Symbol, rhs: Symbol) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
// MARK: Hashable
extension Symbol: Hashable {
public var hashValue: Int {
// Return a hash 'unique' to this object
return ObjectIdentifier(self).hashValue
}
}
|
bsd-3-clause
|
205572e785afe628b4ca60487a9e39cf
| 30.788732 | 79 | 0.737705 | 4.812367 | false | false | false | false |
kazuhidet/fastlane
|
fastlane/swift/RubyCommand.swift
|
5
|
5355
|
// RubyCommand.swift
// Copyright (c) 2020 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
struct RubyCommand: RubyCommandable {
var type: CommandType { return .action }
struct Argument {
enum ArgType {
case stringClosure
var typeString: String {
switch self {
case .stringClosure:
return "string_closure" // this should match when is in ruby's SocketServerActionCommandExecutor
}
}
}
let name: String
let value: Any?
let type: ArgType?
init(name: String, value: Any?, type: ArgType? = nil) {
self.name = name
self.value = value
self.type = type
}
var hasValue: Bool {
return value != nil
}
var json: String {
if let someValue = value {
let typeJson: String
if let type = type {
typeJson = ", \"value_type\" : \"\(type.typeString)\""
} else {
typeJson = ""
}
if type == .stringClosure {
return "{\"name\" : \"\(name)\", \"value\" : \"ignored_for_closure\"\(typeJson)}"
} else if let array = someValue as? [String] {
return "{\"name\" : \"\(name)\", \"value\" : \"\(array.joined(separator: ","))\"\(typeJson)}"
} else if let hash = someValue as? [String: Any] {
let jsonData = try! JSONSerialization.data(withJSONObject: hash, options: [])
let jsonString = String(data: jsonData, encoding: .utf8)!
return "{\"name\" : \"\(name)\", \"value\" : \(jsonString)\(typeJson)}"
} else {
let dictionary = [
"name": name,
"value": someValue,
]
let jsonData = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
let jsonString = String(data: jsonData, encoding: .utf8)!
return jsonString
}
} else {
// Just exclude this arg if it doesn't have a value
return ""
}
}
}
let commandID: String
let methodName: String
let className: String?
let args: [Argument]
let id: String = UUID().uuidString
var closure: ((String) -> Void)? {
let callbacks = args.filter { ($0.type != nil) && $0.type == .stringClosure }
guard let callback = callbacks.first else {
return nil
}
guard let callbackArgValue = callback.value else {
return nil
}
guard let callbackClosure = callbackArgValue as? ((String) -> Void) else {
return nil
}
return callbackClosure
}
func callbackClosure(_ callbackArg: String) -> ((String) -> Void)? {
// WARNING: This will perform the first callback it receives
let callbacks = args.filter { ($0.type != nil) && $0.type == .stringClosure }
guard let callback = callbacks.first else {
verbose(message: "received call to performCallback with \(callbackArg), but no callback available to perform")
return nil
}
guard let callbackArgValue = callback.value else {
verbose(message: "received call to performCallback with \(callbackArg), but callback is nil")
return nil
}
guard let callbackClosure = callbackArgValue as? ((String) -> Void) else {
verbose(message: "received call to performCallback with \(callbackArg), but callback type is unknown \(callbackArgValue.self)")
return nil
}
return callbackClosure
}
func performCallback(callbackArg: String, socket: SocketClient, completion: @escaping () -> Void) {
verbose(message: "Performing callback with: \(callbackArg)")
socket.leave()
callbackClosure(callbackArg)?(callbackArg)
completion()
}
var commandJson: String {
let argsArrayJson = args
.map { $0.json }
.filter { $0 != "" }
let argsJson: String?
if !argsArrayJson.isEmpty {
argsJson = "\"args\" : [\(argsArrayJson.joined(separator: ","))]"
} else {
argsJson = nil
}
let commandIDJson = "\"commandID\" : \"\(commandID)\""
let methodNameJson = "\"methodName\" : \"\(methodName)\""
var jsonParts = [commandIDJson, methodNameJson]
if let argsJson = argsJson {
jsonParts.append(argsJson)
}
if let className = className {
let classNameJson = "\"className\" : \"\(className)\""
jsonParts.append(classNameJson)
}
let commandJsonString = "{\(jsonParts.joined(separator: ","))}"
return commandJsonString
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
|
mit
|
a1080bb195d1d0947c3f274f33587148
| 33.10828 | 139 | 0.537442 | 4.926403 | false | false | false | false |
zef/HTTPStatus
|
Sources/HTTPStatus.swift
|
1
|
10321
|
public struct HTTPStatus {
public let code: Int
public var customMessage: String?
public var message: String {
return HTTPStatus.messages[code] ?? customMessage ?? "Unknown"
}
public init(safeCode code: Int, message: String? = nil) {
precondition(HTTPStatus.codeIsValid(code), "Status Code must be between 100 and 599")
self.code = code
self.customMessage = message
}
public init?(code: Int, message: String? = nil) {
guard HTTPStatus.codeIsValid(code) else { return nil }
self.code = code
self.customMessage = message
}
static func codeIsValid(code: Int) -> Bool {
return 100...599 ~= code
}
}
public extension HTTPStatus {
enum Family: String {
case Informational
case Successful
case Redirection
case ClientError
case ServerError
var range: Range<Int> {
switch self {
case Informational: return 100...199
case Successful: return 200...299
case Redirection: return 300...399
case ClientError: return 400...499
case ServerError: return 500...599
}
}
}
var family: Family {
switch code {
case Family.Informational.range:
return .Informational
case Family.Successful.range:
return .Successful
case Family.Redirection.range:
return .Redirection
case Family.ClientError.range:
return .ClientError
case Family.ServerError.range:
return .ServerError
default:
return .ServerError
}
}
var isInformational: Bool { return family == .Informational }
var isSuccessful: Bool { return family == .Successful }
var isRedirection: Bool { return family == .Redirection }
var isClientError: Bool { return family == .ClientError }
var isServerError: Bool { return family == .ServerError }
}
extension HTTPStatus: IntegerLiteralConvertible {
public init(integerLiteral: Int) {
self.init(safeCode: integerLiteral)
}
}
extension HTTPStatus: CustomStringConvertible {
public var description: String {
return "\(code) \(message)"
}
}
extension HTTPStatus: Equatable {}
public func == (left: HTTPStatus, right: HTTPStatus) -> Bool {
return left.code == right.code
}
extension HTTPStatus: Hashable {
public var hashValue: Int {
return code.hashValue
}
}
extension HTTPStatus {
static var messages = [
100: "Continue",
101: "Switching Protocols",
102: "Processing",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi-Status",
208: "Already Reported",
226: "IM Used",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
306: "Switch Proxy",
307: "Temporary Redirect",
308: "Permanent Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Payload Too Large",
414: "URI Too Long",
415: "Unsupported Media Type",
416: "Range Not Satisfiable",
417: "Expectation Failed",
418: "Im A Teapot",
419: "Authentication Timeout",
421: "Misdirected Request",
422: "Unprocessable Entity",
423: "Locked",
424: "Failed Dependency",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
440: "Login Timeout",
444: "No Response",
449: "Retry With",
451: "Unavailable For Legal Reasons",
494: "Request Header Too Large",
495: "Cert Error",
496: "No Cert",
497: "HTTP To HTTPS",
498: "Token Expired",
499: "Client Closed Request",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
509: "Bandwidth Limit Exceeded",
510: "Not Extended",
511: "Network Authentication Required",
599: "Network Timeout Error"
]
}
public extension HTTPStatus {
static let Continue = HTTPStatus(safeCode: 100)
static let SwitchingProtocols = HTTPStatus(safeCode: 101)
static let Processing = HTTPStatus(safeCode: 102)
static let OK = HTTPStatus(safeCode: 200)
static let Created = HTTPStatus(safeCode: 201)
static let Accepted = HTTPStatus(safeCode: 202)
static let NonAuthoritativeInformation = HTTPStatus(safeCode: 203)
static let NoContent = HTTPStatus(safeCode: 204)
static let ResetContent = HTTPStatus(safeCode: 205)
static let PartialContent = HTTPStatus(safeCode: 206)
static let MultiStatus = HTTPStatus(safeCode: 207)
static let AlreadyReported = HTTPStatus(safeCode: 208)
static let IMUsed = HTTPStatus(safeCode: 226)
static let MultipleChoices = HTTPStatus(safeCode: 300)
static let MovedPermanently = HTTPStatus(safeCode: 301)
static let Found = HTTPStatus(safeCode: 302)
static let SeeOther = HTTPStatus(safeCode: 303)
static let NotModified = HTTPStatus(safeCode: 304)
static let UseProxy = HTTPStatus(safeCode: 305)
static let SwitchProxy = HTTPStatus(safeCode: 306)
static let TemporaryRedirect = HTTPStatus(safeCode: 307)
static let PermanentRedirect = HTTPStatus(safeCode: 308)
static let BadRequest = HTTPStatus(safeCode: 400)
static let Unauthorized = HTTPStatus(safeCode: 401)
static let PaymentRequired = HTTPStatus(safeCode: 402)
static let Forbidden = HTTPStatus(safeCode: 403)
static let NotFound = HTTPStatus(safeCode: 404)
static let MethodNotAllowed = HTTPStatus(safeCode: 405)
static let NotAcceptable = HTTPStatus(safeCode: 406)
static let ProxyAuthenticationRequired = HTTPStatus(safeCode: 407)
static let RequestTimeout = HTTPStatus(safeCode: 408)
static let Conflict = HTTPStatus(safeCode: 409)
static let Gone = HTTPStatus(safeCode: 410)
static let LengthRequired = HTTPStatus(safeCode: 411)
static let PreconditionFailed = HTTPStatus(safeCode: 412)
static let PayloadTooLarge = HTTPStatus(safeCode: 413)
static let URITooLong = HTTPStatus(safeCode: 414)
static let UnsupportedMediaType = HTTPStatus(safeCode: 415)
static let RangeNotSatisfiable = HTTPStatus(safeCode: 416)
static let ExpectationFailed = HTTPStatus(safeCode: 417)
static let ImATeapot = HTTPStatus(safeCode: 418)
static let AuthenticationTimeout = HTTPStatus(safeCode: 419)
static let MisdirectedRequest = HTTPStatus(safeCode: 421)
static let UnprocessableEntity = HTTPStatus(safeCode: 422)
static let Locked = HTTPStatus(safeCode: 423)
static let FailedDependency = HTTPStatus(safeCode: 424)
static let UpgradeRequired = HTTPStatus(safeCode: 426)
static let PreconditionRequired = HTTPStatus(safeCode: 428)
static let TooManyRequests = HTTPStatus(safeCode: 429)
static let RequestHeaderFieldsTooLarge = HTTPStatus(safeCode: 431)
static let LoginTimeout = HTTPStatus(safeCode: 440)
static let NoResponse = HTTPStatus(safeCode: 444)
static let RetryWith = HTTPStatus(safeCode: 449)
static let UnavailableForLegalReasons = HTTPStatus(safeCode: 451)
static let RequestHeaderTooLarge = HTTPStatus(safeCode: 494)
static let CertError = HTTPStatus(safeCode: 495)
static let NoCert = HTTPStatus(safeCode: 496)
static let HTTPToHTTPS = HTTPStatus(safeCode: 497)
static let TokenExpired = HTTPStatus(safeCode: 498)
static let ClientClosedRequest = HTTPStatus(safeCode: 499)
static let InternalServerError = HTTPStatus(safeCode: 500)
static let NotImplemented = HTTPStatus(safeCode: 501)
static let BadGateway = HTTPStatus(safeCode: 502)
static let ServiceUnavailable = HTTPStatus(safeCode: 503)
static let GatewayTimeout = HTTPStatus(safeCode: 504)
static let HTTPVersionNotSupported = HTTPStatus(safeCode: 505)
static let VariantAlsoNegotiates = HTTPStatus(safeCode: 506)
static let InsufficientStorage = HTTPStatus(safeCode: 507)
static let LoopDetected = HTTPStatus(safeCode: 508)
static let BandwidthLimitExceeded = HTTPStatus(safeCode: 509)
static let NotExtended = HTTPStatus(safeCode: 510)
static let NetworkAuthenticationRequired = HTTPStatus(safeCode: 511)
static let NetworkTimeoutError = HTTPStatus(safeCode: 599)
}
|
mit
|
bb6ab417efc3ba4abd5950e8a4ae883c
| 39.794466 | 93 | 0.59035 | 4.872993 | false | false | false | false |
huangenyan/MathSwift
|
MathSwiftTests/MathSwiftTests.swift
|
1
|
9804
|
//
// MathSwiftTests.swift
// MathSwiftTests
//
// Created by Enyan Huang on 10/10/14.
// Copyright (c) 2014 The Hong Kong Polytechnic University. All rights reserved.
//
import UIKit
import XCTest
import MathSwift
class MathSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the 6677invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testMatrixInitByDimension() {
let m = Matrix(rows: 1, columns: 2)
XCTAssert(m.rows == 1, "Rows wrong")
XCTAssert(m.columns == 2, "Columns wrong")
for e in m {
XCTAssert(e.isZero, "Initial value of each element should be 0")
}
}
func testMatrixInitByElements() {
let m = Matrix(elements: [[1,2,3],[4,5,6]])
XCTAssert(m.rows == 2, "Rows wrong")
XCTAssert(m.columns == 3, "Columns wrong")
}
func testSubscriptRead() {
let m = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
XCTAssert(m[0,0].toDouble() == 1, "First element should be 1")
XCTAssert(m[[0,1],[0,1]] == Matrix(elements: [[1,2],[4,5]]), "Upper left 2x2 wrong")
XCTAssert(m[0,[0,1]] == Matrix(elements: [[1,2]]), "Upper left 1x2 wrong")
XCTAssert(m[[0,1],0] == Matrix(elements: [[1],[4]]), "Upper left 2x1 wrong")
}
func testSubscriptWrite() {
var m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
var m2 = m1, m3 = m1, m4 = m1
m1[0,0] = 10
XCTAssert(m1 == Matrix(elements: [[10,2,3],[4,5,6],[7,8,9]]), "First element wrong")
m2[[0,1],[0,1]] = Matrix(elements: [[10,20],[40,50]])
XCTAssert(m2 == Matrix(elements: [[10,20,3],[40,50,6],[7,8,9]]), "Upper left 2x2 wrong")
m3[0,[0,1]] = Matrix(elements: [[10,20]])
XCTAssert(m3 == Matrix(elements: [[10,20,3],[4,5,6],[7,8,9]]), "Upper left 1x2 wrong")
m4[[0,1],0] = Matrix(elements: [[10],[40]])
XCTAssert(m4 == Matrix(elements: [[10,2,3],[40,5,6],[7,8,9]]), "Upper left 2x1 wrong")
}
func testSubscriptRange() {
let m = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
XCTAssert(m[0...1,0...1] == Matrix(elements: [[1,2],[4,5]]), "Upper left 2x2 wrong")
}
func testSubscriptEmpty() {
let m = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
XCTAssert(m[ALL,[0,1]] == Matrix(elements: [[1,2],[4,5],[7,8]]), "Left 2 columns wrong")
}
func testMatrixPlus() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m2 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m3 = Matrix(elements: [[2,4,6],[8,10,12],[14,16,18]])
XCTAssert(m1 + m2 == m3, "Plus result wrong")
}
func testMatrixMinus() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m2 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m3 = Matrix(elements: [[0,0,0],[0,0,0],[0,0,0]])
XCTAssert(m1 - m2 == m3, "Minus result wrong")
}
func testMatrixElementwiseMultiply() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m2 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m3 = Matrix(elements: [[1,4,9],[16,25,36],[49,64,81]])
XCTAssert(m1 *~ m2 == m3, "Multiply result wrong")
}
func testMatrixElementwiseDevide() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m2 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m3 = Matrix(elements: [[1,1,1],[1,1,1],[1,1,1]])
XCTAssert(m1 /~ m2 == m3, "Devide result wrong")
}
func testMatrixElementwiseExp() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m2 = Matrix(elements: [[1,4,9],[16,25,36],[49,64,81]])
XCTAssert(m1 ^~ 2 == m2, "Exp result wrong")
}
func testTanspose() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m2 = Matrix(elements: [[1,4,7],[2,5,8],[3,6,9]])
let m3 = Matrix(elements: [[1,2],[3,4],[5,6]])
let m4 = Matrix(elements: [[1,3,5],[2,4,6]])
XCTAssert(m1.transpose == m2, "Transpose wrong")
XCTAssert(m3.transpose == m4, "Transpose wrong")
}
func testDotProduct() {
let m1 = Matrix(elements: [[1],[2],[3],[4],[5]])
let m2 = Matrix(elements: [[10],[20],[30],[40],[50]])
let result = 550.0
XCTAssert(m1.dot(m2) == result, "Dot product wrong")
}
func testMatrixProduct() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6]])
let m2 = Matrix(elements: [[10,20],[30,40],[50,60]])
let m3 = Matrix(elements: [[220,280],[490,640]])
XCTAssert(m1 * m2 == m3, "Matrix product wrong")
}
func testZeros() {
let m1 = Matrix.zerosWithRows(2, columns: 3)
let m2 = Matrix(elements: [[0,0,0],[0,0,0]])
XCTAssert(m1 == m2, "Zeros wrong")
}
func testOnes() {
let m1 = Matrix.onesWithRows(2, columns: 3)
let m2 = Matrix(elements: [[1,1,1],[1,1,1]])
XCTAssert(m1 == m2, "Ones wrong")
}
func testIdentity() {
let m1 = Matrix.identityWithSize(3)
let m2 = Matrix(elements: [[1,0,0],[0,1,0],[0,0,1]])
XCTAssert(m1 == m2, "Identity wrong")
}
func testDiagonal() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let m1Diag = Matrix(elements: [[1,0,0],[0,5,0],[0,0,9]])
XCTAssert(m1.diagonal == m1Diag, "Diagonal wrong for square matrix")
let m2 = Matrix(elements: [[1,2,3],[4,5,6]])
let m2Diag = Matrix(elements: [[1,0,0],[0,5,0]])
XCTAssert(m2.diagonal == m2Diag, "Diagonal wrong for rectangle matrix (m < n)")
let m3 = Matrix(elements: [[1,2],[3,4],[5,6]])
let m3Diag = Matrix(elements: [[1,0],[0,4],[0,0]])
XCTAssert(m3.diagonal == m3Diag, "Diagonal wrong for rectangle matrix (m > n)")
}
func testDeterminant() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
XCTAssert(doublePrecisionEqual(m1.determinant, 0), "Determinant wrong for singular matrix")
let m2 = Matrix(elements: [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])
XCTAssert(m2.determinant == 1, "Determinant wrong for I(4x4)")
let m3 = Matrix.identityWithSize(5)
XCTAssert(m3.determinant == 1, "Determinant wrong for I(5x5)")
let m4 = Matrix(elements: [[1,2,0],[-1,1,1],[1,2,3]])
XCTAssert(m4.determinant == 9, "Determinant wrong for a 3x3 matrix")
}
func testInverse() {
self.measure() {
let m1 = Matrix.identityWithSize(5)
XCTAssert(m1.inverse == m1, "Inverse wrong for I(5x5)")
let m2 = Matrix(elements: [[1,2,3],[3,2,1],[2,1,3]])
let m2Inv = Matrix(elements: [[-5,3,4],[7,3,-8],[1,-3,4]]) / 12
XCTAssert(m2.inverse == m2Inv, "Inverse wrong for a 3x3 matrix")
}
}
func testReshape() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6]])
let m1Reshape3x2 = Matrix(elements: [[1,2],[3,4],[5,6]])
let m1Reshape1x6 = Matrix(elements: [[1,2,3,4,5,6]])
let m1Reshape6x1 = Matrix(elements: [[1],[2],[3],[4],[5],[6]])
XCTAssert(m1.reshapeToRows(3, columns: 2) == m1Reshape3x2, "Reshape 2x3 to 3x2 wrong")
XCTAssert(m1.reshapeToRows(1, columns: 6) == m1Reshape1x6, "Reshape 2x3 to 1x6 wrong")
XCTAssert(m1.reshapeToRows(6, columns: 1) == m1Reshape6x1, "Reshape 2x3 to 6x1 wrong")
}
func testMatrixConcatenate() {
let m1 = Matrix(elements: [[11,12],[21,22],[31,32]])
let m2 = Matrix(elements: [[13],[23],[33]])
let m3 = Matrix(elements: [[41,42,43]])
let result = Matrix(elements: [[11,12,13],[21,22,23],[31,32,33],[41,42,43]])
XCTAssert(m1 +++ m2 --- m3 == result, "Concatenate wrong")
}
func testReduction() {
let m1 = Matrix(elements: [[1,2,3],[4,5,6]])
let m1Result1 = Matrix(elements: [[5,7,9]])
let m1Result2 = Matrix(elements: [[6],[15]])
XCTAssert(m1.reduceAlongDimension(.column, initial: 0, combine: +) == m1Result1, "Reduce along columns wrong")
XCTAssert(m1.reduceAlongDimension(.row, initial: 0, combine: +) == m1Result2, "Reduce along rows wrong")
}
func testFormat() {
let constant = sqrt(2.0)
let m1 = Matrix(elements: [[constant,0,2.3],[1,constant/2,1.87432],[0,2.5,0]])
print(m1)
}
func testSVDSquareMatrix() {
let m = Matrix(elements: [[1,2,3],[4,5,6],[7,8,9]])
let (U,S,VT) = m.singularValueDecomposition()
XCTAssert(U * U.transpose == Matrix.identityWithSize(m.rows), "U should be orthogonal")
XCTAssert(VT * VT.transpose == Matrix.identityWithSize(m.columns), "V should be orthogonal")
XCTAssert(m == U * S * VT, "M should be equal to U*S*VT")
}
func testSVDGeneralMatrix() {
let m = Matrix(elements: [[1,2],[3,4],[5,6],[7,8]])
let (U,S,VT) = m.singularValueDecomposition()
XCTAssert(U * U.transpose == Matrix.identityWithSize(m.rows), "U should be orthogonal")
XCTAssert(VT * VT.transpose == Matrix.identityWithSize(m.columns), "V should be orthogonal")
XCTAssert(m == U * S * VT, "M should be equal to U*S*VT")
}
func testEigen() {
let m = Matrix(elements: [[1,2],[3,4]])
let (values, vectors) = m.eigen()
XCTAssert(m * vectors[0] == values[0] * vectors[0], "Eigen wrong")
XCTAssert(m * vectors[1] == values[1] * vectors[1], "Eigen wrong")
}
}
|
mit
|
fc96f90224467dc9460ed1141b27b80a
| 40.193277 | 118 | 0.545594 | 2.986293 | false | true | false | false |
sodascourse/swift-introduction
|
Swift-Introduction.playground/Pages/Functions.xcplaygroundpage/Contents.swift
|
1
|
9443
|
/*:
# Functions
Functions are self-contained chunks of code that perform a specific task.
You give a function a name that identifies what it does, and this name is used to “call”
the function to perform its task when needed.
Functions might have input parameters (arguments) and might have a returned result as output.
Every function in Swift has a type, consisting of the function’s parameter types and
return type.
*/
func add(x: Int, y: Int) -> Int {
return x + y
}
let addedResult = add(x: 1, y: 2)
/*:
In above example, we say there's a function named `add` which accepts two arguments:
`x` and `y`. Both the two arguments are integers. The `add` function also returns
an integer result.
And we called the `add` function with `1` and `2` as parameters, and assign the
result of this function to a constant called `addedResult`.
*/
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Parameters
Functions are not required to define input parameters. Here’s a function with no input
parameters, which always returns the same String message whenever it is called.
In this case, this function's name is `sayHello()`
*/
func sayHello() -> String {
return "Hello"
}
sayHello()
/*:
Functions can have multiple input parameters, which are written within
the function’s parentheses, separated by commas.
In this case, this function's name is `multiply(x:y:)`
*/
func multiply(x: Int, y: Int) -> Int {
return x * y
}
multiply(x: 6, y: 7)
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Return value
Functions are not required to define a return type.
*/
func doNothing() {
}
/*:
For functions which return a value, we use arrow (`->`) to indicate the type of return value,
and use `return` keyword to specify the value as output.
Functions would stop execution after a `return` statement is executed.
*/
func subtract(x: Int, y: Int) -> Int {
return x - y
}
let answer = subtract(x: 50, y: 8)
//: > Try to add a line after the `return` statement in `subtract(x:y:)` function. See what Xcode says
/*:
Functions could return multiple values as results via tuples
*/
func divide(x: Int, y: Int) -> (quotient: Int, remainder: Int) {
let quotient = x / y
let remainders = x % y
return (quotient, remainders)
}
let divideResult1 = divide(x: 22, y: 7)
divideResult1.quotient
divideResult1.remainder
let (divideQuotient1, divideRemainders1) = divide(x: 50, y: 6)
divideQuotient1
divideRemainders1
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Argument Labels and Parameter Names
Each function parameter has both an argument label and a parameter name.
The argument label is used when calling the function; each argument is written in
the function call with its argument label before it. The parameter name is used in the
implementation of the function.
By default, parameters use their parameter name as their argument label.
*/
func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
greet(person: "Peter", from: "Tokyo")
/*:
In above function, we say:
1. This function is named: `greet(person:from:)`
2. It takes two parameters, both are strings, and returns a String value.
3. The **parameter name** of the first parameter is `person` and its argument label
is also `person`.
4. The **parameter name** of the first parameter is `hometown` and its argument label
is `from`.
The parameter name is used when writing the implementation of the function.
And the argument label is used when calling the function.
By using argument labels makes the statement of calling a function fit to English grammar,
and using parameter names provides clear syntax when implementing functions.
*/
func bad_move1(from: String, to: String) -> String {
return "Moving from \(from) to \(to)."
}
bad_move1(from: "Tokyo", to: "Osaka")
func bad_move2(origin: String, destination: String) -> String {
return "Moving from \(origin) to \(destination)."
}
bad_move2(origin: "Tokyo", destination: "Osaka")
func move(from origin: String, to destination: String) -> String {
return "Moving from \(origin) to \(destination)."
}
move(from: "Tokyo", to: "Osaka")
/*:
### Omit argument labels
Sometimes the argument label would make the sentence redundant, we can use `_` to omit it.
In following case, the function name is `divide(_:by:)`
> In Swift, `_` is used to omit values.
*/
func divide(_ x: Int, by y: Int) -> (Int, Int) {
return (x/y, x%y)
}
divide(25, by: 4)
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Default value of parameters
You can define a default value for any parameter in a function by assigning
a value to the parameter after that parameter’s type. If a default value is defined,
you can omit that parameter when calling the function.
*/
func greet(to person: String, with message: String = "Hello") -> String {
return "\(message) \(person)!"
}
greet(to: "Peter")
greet(to: "Emma", with: "Hi")
//: --------------------------------------------------------------------------------------------------------------------
/*:
## Scope of variables
In Swift, variables and costants have scope to live, usually the code block defined by
the curly brackets (`{}`).
A variable/constant can be accessed only in the same scope or the children scopes. It
cannot be accessed in outer scope. Also, the value its stored would be freed or destroyed
after leaving the scope.
Parameters of a function are live in the scope of the function.
*/
let meltingPointInFahrenheit = 32.0
func convertToCelsius(from fahrenheit: Double) -> Double {
let factor = 100.0 / 180.0
return (fahrenheit - meltingPointInFahrenheit) * factor
}
convertToCelsius(from: 68)
//fahrenheit // Try to uncomment this line to see what Xcode yields
//factor // Try to uncomment this line to see what Xcode yields
//: --------------------------------------------------------------------------------------------------------------------
//: # Advanced topics
//: --------------------------------------------------------------------------------------------------------------------
/*:
### Variadic Parameters
A variadic parameter accepts zero or more values of a specified type.
You use a variadic parameter to specify that the parameter can be passed a
varying number of input values when the function is called.
Write variadic parameters by inserting three period characters (`...`) after the parameter’s type name.
*/
func average(_ numbers: Double...) -> Double {
// `numbers` here is an array of Double.
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
average(1, 2, 3, 4, 5)
//: --------------------------------------------------------------------------------------------------------------------
/*:
### In-Out Parameters
Function parameters are constants by default. Trying to change the value of
a function parameter from within the body of that function results in a compile-time error.
This means that you can’t change the value of a parameter by mistake.
If you want a function to modify a parameter’s value,
and you want those changes to persist after the function call has ended,
define that parameter as an in-out parameter instead.
*/
// Try to uncomment following function to see the error message from Xcode
//func broken_swap(_ a: Int, _ b: Int) {
// let temporaryA = a
// a = b
// b = temporaryA
//}
func swapTwoNumbers(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var firstInt = 42
var secondInt = 2000
swapTwoNumbers(&firstInt, &secondInt)
firstInt
secondInt
//: --------------------------------------------------------------------------------------------------------------------
/*:
### Overloading
Function overloading is the ability to create multiple functions of the same name with different implementations.
Calls to an overloaded function will run a specific implementation of that function appropriate to
the context of the call, allowing one function call to perform different tasks depending on context.
*/
func swapTwoNumbers(_ a: inout Double, _ b: inout Double) {
let temporaryA = a
a = b
b = temporaryA
}
var firstDouble = 42.0
var secondDouble = 24.0
swapTwoNumbers(&firstDouble, &secondDouble)
//: --------------------------------------------------------------------------------------------------------------------
/*:
### Arguments with Generic Types
Generics provides the ability to have a single implementation that works for all possible types.
See `Generic` page for more detail information
*/
func mySwap<T>(_ a: inout T, _ b: inout T) {
let tempA = a
a = b
b = tempA
}
var firstPeople = "Peter"
var secondPeople = "Rebecca"
mySwap(&firstPeople, &secondPeople)
firstPeople
secondPeople
var firstPrice = 1950
var secondPrice = 2450
mySwap(&firstPrice, &secondPrice)
firstPrice
secondPrice
//: ---
//:
//: [<- Previous](@previous) | [Next ->](@next)
//:
|
apache-2.0
|
1d2ad21eb0579073668e1a2032050fa2
| 29.208333 | 120 | 0.618249 | 4.39804 | false | false | false | false |
MengQuietly/MQDouYuTV
|
MQDouYuTV/MQDouYuTV/Classes/Tools/Extension/UIBarButtonItem+Extension.swift
|
1
|
1517
|
//
// UIBarButtonItem+Extension.swift
// MQDouYuTV
//
// Created by mengmeng on 16/9/22.
// Copyright © 2016年 mengQuietly. All rights reserved.
//
import UIKit
/** UIBarButtonItem + Extension */
extension UIBarButtonItem {
/* 类方法:创建自定义View
class func creatItem(imageName: String, hightImageName: String = "", size: CGSize = CGSize.zero) -> UIBarButtonItem {
let navBtnItem = UIButton(type: .custom)
navBtnItem.setImage(UIImage(named: imageName), for: .normal)
if hightImageName != "" {
navBtnItem.setImage(UIImage(named: hightImageName), for: .highlighted)
}
if size == CGSize.zero {
navBtnItem.sizeToFit()
} else {
navBtnItem.frame = CGRect(origin: .zero, size: size)
}
return UIBarButtonItem(customView: navBtnItem)
}*/
//MARK:-barBtnItem:默认图、高亮图、Size
convenience init(imageName: String, hightImageName: String = "", size: CGSize = CGSize.zero) {
let navBtnItem = UIButton(type: .custom)
navBtnItem.setImage(UIImage(named: imageName), for: .normal)
if hightImageName != "" {
navBtnItem.setImage(UIImage(named: hightImageName), for: .highlighted)
}
if size == CGSize.zero {
navBtnItem.sizeToFit()
} else {
navBtnItem.frame = CGRect(origin: .zero, size: size)
}
self.init(customView: navBtnItem)
}
}
|
mit
|
46041ced901d07095a3fd95a0a33c508
| 29.163265 | 121 | 0.600812 | 4.334311 | false | false | false | false |
m4rr/MosCoding
|
(Summer)/Converter/Converter/ViewController.swift
|
1
|
3117
|
//
// ViewController.swift
// Converter
//
// Created by Marat S. on 20/08/2016.
// Copyright © 2016 m4rr. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var dateLabel: UILabel!
var tCelsius: [TempUnit] = []
let calc = Calculator()
@IBAction func buttonTap(sender: AnyObject) {
UIView.animateWithDuration(2) {
self.pickerView.alpha = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
let lowerBound = -100
let upperBound = 100
//let range = lowerBound...upperBound
let range = lowerBound.stride(to: upperBound, by: 5)
for index in range {
// TempUnit(temp: Double(100500))
let unit = TempUnit(temp: Double(index))
tCelsius.append(unit)
}
pickerView.dataSource = self
pickerView.delegate = self
let defaults = NSUserDefaults.standardUserDefaults()
let retrievedValue = defaults.integerForKey("selectedRow")
pickerView.selectRow(retrievedValue, inComponent: 0, animated: true)
label.text = defaults.objectForKey("textValue") as? String
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return tCelsius.count
}
}
extension ViewController: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let temp = tCelsius[row]
// let rounded = calc.prettyRound(temp)
let rounded = temp.prettyRound()
return rounded + " °C"
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
/// получаем объект `TempUnit` из списка `tCelsius` по номеру `row`
let unitCelsius = tCelsius[row]
/// получаем значение температуры из объекта типа `TempUnit`
let degree = unitCelsius.temp
/// конвертируем значение температуы °C → °F
let degreeInF = calc.convert(celsius: degree)
/// создаем объект `TempUnit` со сконвертированным значением температуры
let unitFahr = TempUnit(temp: degreeInF)
/// получаем от объекта `TempUnit` отформатированную строку
let textValue = unitFahr.prettyRound()
/// ставим отформатированную строку в `label.text`
label.text = textValue + " °F"
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(row, forKey: "selectedRow")
defaults.setObject(textValue, forKey: "textValue")
let dateNow = NSDate()
dateLabel.text = "\(dateNow)"
}
}
|
mit
|
176ffff9b29b0f25098c919f0cd28df7
| 20.392593 | 107 | 0.696676 | 4.03352 | false | false | false | false |
PureSwift/Bluetooth
|
Sources/BluetoothGATT/GATTAggregateFormatDescriptor.swift
|
1
|
2211
|
//
// GATTAggregateFormatDescriptor.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// GATT Characteristic Aggregate Format Descriptor
///
/// The Characteristic Aggregate Format descriptor defines the format of an aggregated Characteristic Value.
///
/// Only one Characteristic Aggregate Format descriptor exists in a characteristic definition.
/// This descriptor consists of a list of Attribute Handles pointing to Characteristic Presentation Format declarations.
/// This descriptor is read only and does not require authentication or authorization.
/// The list of Attribute Handles is the concatenation of multiple 16-bit Attribute Handle values into a single Attribute Value.
/// If more than one Characteristic Presentation Format declarations exist, then there is one Characteristic Aggregate Format declaration.
/// However, a Characteristic Aggregate Format descriptor can be present even if there aren't any Presentation Format descriptors in the characteristic definition. The order of the Attribute Handles in the list is significant.
///
/// Example:
/// If 3 Characteristic Presentation Format declarations exist at Attribute Handles 0x40, 0x50 and 0x60,
/// the Characteris Aggregate Format Value is 0x405060.
@frozen
public struct GATTAggregateFormatDescriptor: GATTDescriptor {
public static let uuid: BluetoothUUID = .characteristicAggregateFormat
public var handles: [UInt16]
public init(handles: [UInt16] = []) {
self.handles = handles
}
public init?(data: Data) {
// this is not actually UInt16 UUID, but handles
// since the binary format is the same we can reuse code
guard let list = GAPUUIDList<UInt16>(data: data)
else { return nil }
self.handles = list.uuids
}
public var data: Data {
return Data(GAPUUIDList<UInt16>(uuids: handles))
}
public var descriptor: GATTAttribute.Descriptor {
return GATTAttribute.Descriptor(
uuid: type(of: self).uuid,
value: data,
permissions: [.read]
)
}
}
|
mit
|
dff12460506de53910c66130ebac4cc6
| 37.77193 | 226 | 0.71267 | 5 | false | false | false | false |
kirayamato1989/KYPhotoBrowser
|
KYPhotoBrowser/KYPhotoBrowser.swift
|
1
|
17161
|
//
// PhotoBrowserController.swift
// FEAlbum
//
// Created by YamatoKira on 2016/9/23.
// Copyright © 2016年 feeling. All rights reserved.
//
import Foundation
import KYCircularProgress
/// actions
///
/// - oneTap: 单击了图片
/// - longPress: 长按了图片
/// - dismiss: 浏览器调用了dismiss方法
/// - displayPageChanged: 展示的图片改变
public enum KYPhotoBrowserEvent {
case oneTap(index: Int)
case longPress(index: Int)
case dismiss
case displayPageChanged(index: Int)
var index: Int {
switch self {
case .oneTap(index: let idx):
return idx
case .longPress(index: let idx):
return idx
case .displayPageChanged(index: let idx):
return idx
default:
return 0
}
}
}
public typealias KYPhotoBrowserEventMonitor = ((_ browser: KYPhotoBrowser, _ action: KYPhotoBrowserEvent) -> Void)
/// 图片浏览器
public class KYPhotoBrowser: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
// MARK: public properties
/// 浏览器的行为监视
public var eventMonitor: KYPhotoBrowserEventMonitor?
// public properties
/// 图片间距
public var spacing: CGFloat = 20 {
// change layout
didSet {
_updateCollectionViewLayout()
}
}
/// 当前图片索引
public var currentPage: Int {
return storedCurrentPage
}
/// 当前图片
public var currentPhoto: KYPhotoSource {
return storedPhotos[currentPage]
}
/// 总共有多少图片
public var numberOfPhoto: Int {
return storedPhotos.count
}
/// 是否隐藏完成按钮
public var doneButtonHide: Bool {
set {
doneButton.isHidden = newValue
}
get {
return doneButton.isHidden
}
}
// MARK: private properties
/// 记录当前在第几个图片
fileprivate var storedCurrentPage: Int = 0 {
didSet {
eventMonitor?(self, .displayPageChanged(index: storedCurrentPage))
}
}
/// 图片数据源
fileprivate var storedPhotos: [KYPhotoSource] = []
private var layout: UICollectionViewFlowLayout!
private var collectionView: UICollectionView!
private let doneButton: UIButton = UIButton()
// MARK: initialize
public init(photos: [KYPhotoSource], initialIndex: Int) {
super.init(nibName: nil, bundle: nil)
storedPhotos += photos
storedCurrentPage = initialIndex
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: lifeCycle
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.isStatusBarHidden = false
navigationController?.navigationBar.isHidden = false
}
override public func viewDidLoad() {
super.viewDidLoad()
_initUI()
}
override public func didReceiveMemoryWarning() {
for i in 0..<storedPhotos.count {
let p = storedPhotos[i]
var needRelease = true
if i == currentPage || i == currentPage - 1 || i == currentPage + 1 {
needRelease = false
}
if needRelease {
p.releaseImage()
}
}
}
// MARK: override
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// 移动到当前索引页
_scrollTo(index: currentPage, animated: false)
}
// MARK: public method
/// 根据索引获取Photo实体
///
/// - Parameter index: 索引
/// - Returns: 数据源
public func photoAtIndex(_ index: Int) -> KYPhotoSource? {
guard index > 0 , index < storedPhotos.count else {
return nil
}
return storedPhotos[index]
}
/// 删除某个图片
///
/// - parameter index: 索引
public func removePhoto(at index: Int) {
storedPhotos.remove(at: index)
collectionView?.deleteItems(at: [IndexPath(item: index, section: 0)])
// 防止最后一个被删除时崩溃
if storedCurrentPage >= storedPhotos.count {
storedCurrentPage = storedPhotos.count > 0 ? storedCurrentPage - 1 : 0
}
}
// MARK: UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return storedPhotos.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PhotoBrowserCell
c.oneTapClosure = { [weak self](source, cell) in
if let _ = self {
self!.eventMonitor?(self!, .oneTap(index: indexPath.row))
}
}
c.longPressClosure = { [weak self](source, cell) in
if let _ = self {
self!.eventMonitor?(self!, .longPress(index: indexPath.row))
}
}
let photo = storedPhotos[indexPath.row]
c.source = photo
return c
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let containerW = scrollView.bounds.size.width
if containerW <= 0 {return}
let contentOffset = scrollView.contentOffset
let newIndex = Int((contentOffset.x + containerW / 2) / containerW)
if newIndex != storedCurrentPage {
storedCurrentPage = newIndex
}
}
// MARK: private method
private func _initUI() {
//
view.backgroundColor = .white
automaticallyAdjustsScrollViewInsets = false
//
layout = UICollectionViewFlowLayout()
layout?.scrollDirection = .horizontal
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout!)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView?.register(PhotoBrowserCell.self, forCellWithReuseIdentifier: "cell")
collectionView?.backgroundColor = .black
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.isPagingEnabled = true
collectionView?.showsVerticalScrollIndicator = false
collectionView?.showsHorizontalScrollIndicator = false
view.addSubview(collectionView!)
//
_updateCollectionViewLayout()
//
if navigationController == nil {
// 添加一个返回按钮
doneButton.frame = CGRect(x: 10, y: 10, width: 60, height: 44)
doneButton.setTitle("Done", for: .normal)
doneButton.setTitleColor(.lightGray, for: .normal)
view.addSubview(doneButton)
doneButton.addTarget(self, action: #selector(KYPhotoBrowser._dismiss), for: .touchUpInside)
}
}
/// 更新collectionView的布局
private func _updateCollectionViewLayout() {
let spacing = max(self.spacing, 0)
// 左右偏移是为了解决分页的问题
collectionView?.frame = CGRect(x: -spacing / 2.0, y: 0, width: view.frame.width + spacing, height: view.frame.height)
// 注意这里设置minimumInteritemSpacing是不起作用的,因为是horizon布局
layout?.minimumLineSpacing = spacing
layout?.sectionInset = UIEdgeInsetsMake(0, spacing / 2.0, 0, spacing / 2.0)
layout?.itemSize = UIScreen.main.bounds.size
collectionView?.reloadData()
}
/// 滑动到某个索引
///
/// - Parameters:
/// - index: 目标索引
/// - animated: 是否动画
private func _scrollTo(index: Int, animated: Bool) {
if let _ = collectionView {
let contentOffsetX = collectionView!.bounds.size.width * CGFloat(index)
UIView.animate(withDuration: animated ? 0.4 : 0.0) {
self.collectionView?.contentOffset = CGPoint(x: contentOffsetX, y: 0)
}
}
}
/// 更新title
private func _updateTitle() {
// 置nil
if storedPhotos.count < 2 {
title = nil
return
}
// change title
title = String(format: "%i / %i", currentPage + 1, storedPhotos.count)
}
private func _hideOrShowNavbarAndToolbar() {
let hidden = UIApplication.shared.isStatusBarHidden
UIApplication.shared.isStatusBarHidden = !hidden
if let nav = self.navigationController {
nav.setNavigationBarHidden(!hidden, animated: true)
}
}
@objc private func _dismiss() {
self.dismiss(animated: true, completion: nil)
}
deinit {
// 释放所有的大图
storedPhotos.forEach { (p) in
p.releaseImage()
}
}
}
/// 用于显示照片的cell
fileprivate typealias PhotoBrowserCellActionClosure = ((KYPhotoSource?, UICollectionViewCell) -> Void)
fileprivate class PhotoBrowserCell: UICollectionViewCell, UIScrollViewDelegate, UIGestureRecognizerDelegate {
// 外层用于放大缩小的scrollView
fileprivate let scrollWrapper: UIScrollView = UIScrollView()
let imageView: UIImageView = UIImageView()
var oneTapClosure: PhotoBrowserCellActionClosure?
var doubleTapClosure: PhotoBrowserCellActionClosure?
var longPressClosure: PhotoBrowserCellActionClosure?
let progressView: KYCircularProgress = {
let view = KYCircularProgress(frame: CGRect(x: 0, y: 0, width: 44, height: 44), showGuide: true)
view.colors = [.gray]
view.guideColor = .white
view.guideLineWidth = 3
view.lineWidth = 3
view.startAngle = -.pi/2
view.endAngle = 3 * .pi/2
return view
}()
//
var source: KYPhotoSource? {
didSet{
displaySource()
if source?.image == nil {
source?.loadIfNeed(progress: { [weak self](source, current, total) in
if let _ = self, self?.source?.url == source.url {
self?.progressView.progress = Double(current) / Double(total)
}
}, complete: { [weak self](source, image, error) in
if let _ = self, self?.source?.url == source.url {
self?.displaySource()
}
})
}
}
}
// MARK: init
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initUI()
}
// MARK: override
override func prepareForReuse() {
super.prepareForReuse()
source = nil
imageView.image = nil
progressView.isHidden = true
progressView.progress = 0
}
// MARK: public method
// MARK: UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
if scrollView == scrollWrapper {
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
// MARK: override
override func layoutSubviews() {
super.layoutSubviews()
scrollWrapper.layoutSubviews()
// make center
let centerX = max(scrollWrapper.frame.width, scrollWrapper.contentSize.width) / 2.0
let centerY = max(scrollWrapper.frame.height, scrollWrapper.contentSize.height) / 2.0
imageView.center = CGPoint(x: centerX, y: centerY)
}
// MARK: UIGesture
@objc private func oneTap(sender: UITapGestureRecognizer) {
if sender.state == .ended {
oneTapClosure?(source, self)
}
}
@objc private func doubleTap(sender: UITapGestureRecognizer) {
if sender.state == .ended {
// scale
if scrollWrapper.zoomScale == scrollWrapper.maximumZoomScale {
scrollWrapper.setZoomScale(scrollWrapper.minimumZoomScale, animated: true)
}
else {
let point = sender.location(in: imageView)
scrollWrapper.zoom(to: CGRect(x: point.x, y: point.y, width: 1, height: 1), animated: true)
}
doubleTapClosure?(source, self)
}
}
@objc private func longPress(sender: UILongPressGestureRecognizer) {
if sender.state == .began {
longPressClosure?(source, self)
}
}
// MARK: private method
private func initUI() {
scrollWrapper.maximumZoomScale = 1.5
scrollWrapper.showsVerticalScrollIndicator = false
scrollWrapper.showsHorizontalScrollIndicator = false
scrollWrapper.delegate = self
scrollWrapper.backgroundColor = self.backgroundColor
scrollWrapper.frame = contentView.bounds
scrollWrapper.autoresizingMask = [.flexibleHeight, .flexibleWidth]
contentView.addSubview(scrollWrapper)
//
imageView.frame = scrollWrapper.bounds
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = true
scrollWrapper.addSubview(imageView)
//
progressView.center = CGPoint(x: imageView.bounds.width / 2, y: imageView.bounds.height / 2)
progressView.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin]
imageView.addSubview(progressView)
// tap
let oneTap = UITapGestureRecognizer(target: self, action: #selector(PhotoBrowserCell.oneTap(sender:)))
oneTap.numberOfTapsRequired = 1
oneTap.delegate = self
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(PhotoBrowserCell.doubleTap(sender:)))
doubleTap.numberOfTapsRequired = 2
doubleTap.delegate = self
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(PhotoBrowserCell.longPress(sender:)))
oneTap.require(toFail: doubleTap)
doubleTap.require(toFail: longPress)
addGestureRecognizer(oneTap)
addGestureRecognizer(doubleTap)
addGestureRecognizer(longPress)
}
// 显示当前源
private func displaySource() {
if let _ = source {
scrollWrapper.maximumZoomScale = 1
scrollWrapper.minimumZoomScale = 1
scrollWrapper.zoomScale = 1
progressView.isHidden = false
if let image = source?.image {
// 隐藏
progressView.isHidden = true
imageView.image = image
let imageSize = image.size
var imageViewFrame: CGRect = .zero
imageViewFrame.size = imageSize
scrollWrapper.contentSize = imageSize
imageView.frame = imageViewFrame
setMaxMinScale()
}
else if let holder = source?.placeholder {
imageView.image = holder
imageView.frame = scrollWrapper.bounds
scrollWrapper.contentSize = scrollWrapper.bounds.size
}
}
layoutIfNeeded()
}
private func setMaxMinScale() {
if let image = source?.image {
let imageSize = image.size
let xScale = scrollWrapper.bounds.width / imageSize.width
let yScale = scrollWrapper.bounds.height / imageSize.height
let minScale = min(xScale, yScale)
let maxScale = max(yScale, 2 * minScale)
// caculate fullScreen scale
let fullScreenScale = scrollWrapper.bounds.width / imageSize.width
scrollWrapper.minimumZoomScale = minScale
scrollWrapper.maximumZoomScale = maxScale
scrollWrapper.zoomScale = fullScreenScale
// 如果是高图,默认置顶
scrollWrapper.contentOffset = .zero
// reset position
imageView.frame.origin.x = 0
imageView.frame.origin.y = 0
setNeedsLayout()
}
}
}
|
mit
|
3edb0e9e856fcfc434975d647833a196
| 28.88551 | 128 | 0.577577 | 5.290057 | false | false | false | false |
Stitch7/Instapod
|
Instapod/ViewFromNib.swift
|
1
|
1189
|
//
// ViewFromNib.swift
// Instapod
//
// Created by Christopher Reitz on 30.11.15.
// Copyright © 2015 Christopher Reitz. All rights reserved.
//
import UIKit
class ViewFromNib: UIView {
// MARK: - Properties
var view: UIView!
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
nibInit()
initialize()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
nibInit()
initialize()
}
func nibInit() {
view = loadViewFromNib()
view.frame = bounds
view.clipsToBounds = true
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
func initialize() {
// feel free to override in subclass
}
}
|
mit
|
2d4866b33be010d048164151839bd9fe
| 21.415094 | 101 | 0.618687 | 4.449438 | false | false | false | false |
AlesTsurko/DNMKit
|
DNM_iOS/DNM_iOS/InstrumentString.swift
|
1
|
10569
|
//
// InstrumentString.swift
// denm_view
//
// Created by James Bean on 10/12/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import QuartzCore
import DNMModel
public class InstrumentString: InstrumentView {
// sounding pitch graph
// fingered pitch graph
public var staff_soundingPitch: Graph?
public var staff_fingeredPitch: Graph?
public var tablature: GraphContinuousController?
public override init() { super.init() }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public override init(layer: AnyObject) { super.init(layer: layer) }
public override func createGraphsWithComponent(component: Component, andG g: CGFloat) {
if !component.isGraphBearing { return }
switch component {
case is ComponentPitch, is ComponentStringArtificialHarmonic, is ComponentRest:
if graphByID["soundingPitch"] == nil {
let soundingPitch = Staff(id: "soundingPitch", g: g)
if let (clefType, transposition, _) = instrumentType?
.preferredClefsAndTransposition.first
{
soundingPitch.id = "soundingPitch"
soundingPitch.pad_bottom = g
soundingPitch.pad_top = g
soundingPitch.addClefWithType(clefType, withTransposition: transposition, atX: 15)
addGraph(soundingPitch, isPrimary: false)
staff_soundingPitch = soundingPitch
}
else { fatalError("Can't find a proper clef and transposition") }
}
if graphByID["fingeredPitch"] == nil {
let fingeredPitch = Staff(id: "fingeredPitch", g: g)
if let (clefType, transposition, _) = instrumentType?
.preferredClefsAndTransposition.first
{
fingeredPitch.id = "fingeredPitch"
fingeredPitch.pad_bottom = g
fingeredPitch.pad_top = g
fingeredPitch.addClefWithType(clefType,
withTransposition: transposition, atX: 15
) // HACK
addGraph(fingeredPitch)
staff_fingeredPitch = fingeredPitch
}
else { fatalError("Can't find a proper clef and transposition") }
}
case is ComponentGraphNode:
if graphByID["node"] == nil {
let graph = GraphContinuousController(id: "node")
graph.height = 25 // hack
graph.pad_bottom = 5 // hack
graph.pad_top = 5 // hack
graph.addClefAtX(15) // hack
addGraph(graph)
}
case is ComponentWaveform:
if graphByID["wave"] == nil {
let graph = GraphWaveform(id: "wave", height: 60, width: frame.width) // hack
graph.addClefAtX(15) // hack
addGraph(graph)
}
default: break
}
// TODO: flesh out -- reimplement
/*
switch component.property {
case .Pitch, .StringArtificialHarmonic:
if graphByID["soundingPitch"] == nil {
let soundingPitch = Staff(id: "soundingPitch", g: g)
if let (clefType, transposition, _) = instrumentType?
.preferredClefsAndTransposition.first
{
soundingPitch.id = "soundingPitch"
soundingPitch.pad_bottom = g
soundingPitch.pad_top = g
soundingPitch.addClefWithType(clefType, withTransposition: transposition, atX: 15)
addGraph(soundingPitch, isPrimary: false)
staff_soundingPitch = soundingPitch
}
else { fatalError("Can't find a proper clef and transposition") }
}
if graphByID["fingeredPitch"] == nil {
let fingeredPitch = Staff(id: "fingeredPitch", g: g)
if let (clefType, transposition, _) = instrumentType?
.preferredClefsAndTransposition.first
{
fingeredPitch.id = "fingeredPitch"
fingeredPitch.pad_bottom = g
fingeredPitch.pad_top = g
fingeredPitch.addClefWithType(clefType,
withTransposition: transposition, atX: 15
) // HACK
addGraph(fingeredPitch)
staff_fingeredPitch = fingeredPitch
}
else { fatalError("Can't find a proper clef and transposition") }
}
/*
case .Pitch:
// CREATE GRAPH IF NECESSARY
if graphByID["staff"] == nil {
let staff = Staff(id: "staff", g: g)
if let (clefType, transposition, _) = instrumentType?
.preferredClefsAndTransposition.first
{
staff.id = "staff" // hack
staff.pad_bottom = g
staff.pad_top = g
staff.addClefWithType(clefType, withTransposition: transposition, atX: 15) // HACK
addGraph(staff)
}
else { fatalError("Can't find a proper clef and transposition") }
}
*/
case .Node:
if graphByID["node"] == nil {
let graph = GraphContinuousController(id: "node")
graph.height = 25 // hack
graph.pad_bottom = 5 // hack
graph.pad_top = 5 // hack
graph.addClefAtX(15) // hack
addGraph(graph)
}
case .Wave:
if graphByID["wave"] == nil {
let graph = GraphWaveform(id: "wave", height: 60, width: frame.width) // hack
graph.addClefAtX(15) // hack
addGraph(graph)
}
default: break
}
// ------------------------------------------------------------------------------------
*/
}
public override func createInstrumentEventWithComponent(component: Component,
atX x: CGFloat, withStemDirection stemDirection: StemDirection
) -> InstrumentEvent?
{
switch component {
case is ComponentRest:
// clean this all up please
let instrumentEvent = InstrumentEvent(x: x, stemDirection: stemDirection)
if let fingeredPitch = graphByID["fingeredPitch"] {
let graphEvent = fingeredPitch.startRestAtX(x, withStemDirection: stemDirection)
instrumentEvent.addGraphEvent(graphEvent)
}
instrumentEvent.instrument = self
return instrumentEvent
case is ComponentPitch:
let instrumentEvent = InstrumentEvent(x: x, stemDirection: stemDirection)
if let fingeredPitch = graphByID["fingeredPitch"] {
let graphEvent = fingeredPitch.startEventAtX(x, withStemDirection: stemDirection)
instrumentEvent.addGraphEvent(graphEvent)
}
if let soundingPitch = graphByID["soundingPitch"] {
let graphEvent = soundingPitch.startEventAtX(x, withStemDirection: stemDirection)
graphEvent.isConnectedToStem = false
graphEvent.s = 0.75
instrumentEvent.addGraphEvent(graphEvent)
}
instrumentEvent.instrument = self
return instrumentEvent
case is ComponentStringArtificialHarmonic: break
case is ComponentGraphNode: break
case is ComponentWaveform: break
default: break
}
/*
//let pID = component.pID, iID = component.iID
switch component.property {
case .Pitch, .StringArtificialHarmonic:
let instrumentEvent = InstrumentEvent(x: x, stemDirection: stemDirection)
if let fingeredPitch = graphByID["fingeredPitch"] {
let graphEvent = fingeredPitch.startEventAtX(x, withStemDirection: stemDirection)
instrumentEvent.addGraphEvent(graphEvent)
}
if let soundingPitch = graphByID["soundingPitch"] {
let graphEvent = soundingPitch.startEventAtX(x, withStemDirection: stemDirection)
graphEvent.isConnectedToStem = false
graphEvent.s = 0.75
instrumentEvent.addGraphEvent(graphEvent)
}
instrumentEvent.instrument = self
return instrumentEvent
/*
if let staff = graphByID["staff"] {
let graphEvent = staff.startEventAtX(x, withStemDirection: stemDirection)
let instrumentEvent = InstrumentEvent(x: x, stemDirection: stemDirection)
instrumentEvent.instrument = self
// for now, just add the single graph event
instrumentEvent.addGraphEvent(graphEvent)
print("instrumentEvent: \(instrumentEvent)")
return instrumentEvent
}
*/
case .Node(let value):
assert(graphByID["node"] != nil, "can't find node graph")
if let graph = graphByID["node"] {
let graphEvent = (graph as? GraphContinuousController)!.addNodeEventAtX(x,
withValue: value, andStemDirection: stemDirection
)
let instrumentEvent = InstrumentEvent(x: x, stemDirection: stemDirection)
instrumentEvent.instrument = self
// for now, just add the single graph event
instrumentEvent.addGraphEvent(graphEvent)
return instrumentEvent
}
/*
case .Wave:
assert(graphByID["wave"] != nil, "can't find wave graph")
if let graph = graphByID["wave"] {
let graphEvent = (graph as? GraphWaveform)?.addSampleWaveformAtX(x,
withDuration: Duration(2,8), andBeatWidth: 120
) // HACK
return graphEvent
}
*/
default:
break
}
*/
return nil
}
}
|
gpl-2.0
|
a266467be014c2a8e6b72718b19b8f8e
| 40.120623 | 102 | 0.53293 | 5.029986 | false | false | false | false |
LeeroyDing/Bond
|
Bond/OSX/Bond+NSImageView.swift
|
12
|
2159
|
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tony Arnold (@tonyarnold)
//
// 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 Cocoa
var imageDynamicHandleNSImageView: UInt8 = 0;
extension NSImageView: Bondable, Dynamical {
public var designatedDynamic: Dynamic<NSImage?> {
return self.dynImage
}
public var designatedBond: Bond<NSImage?> {
return self.designatedDynamic.valueBond
}
public var dynImage: Dynamic<NSImage?> {
if let d: AnyObject = objc_getAssociatedObject(self, &imageDynamicHandleNSImageView) {
return (d as? Dynamic<NSImage?>)!
} else {
let d = InternalDynamic<NSImage?>(self.image)
let bond = Bond<NSImage?>() { [weak self] v in
if let s = self {
s.image = v
}
}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &imageDynamicHandleNSImageView, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
}
|
mit
|
0afadca66e9bbecd1cf12152adda26d1
| 36.877193 | 136 | 0.675776 | 4.451546 | false | false | false | false |
tianbinbin/DouYuShow
|
DouYuShow/DouYuShow/Classes/Home/View/RecommendCycleView.swift
|
1
|
4258
|
//
// RecommendCycleView.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/6/10.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
private let kCycleCellID = "kCycleCellID"
class RecommendCycleView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pagecontrollr: UIPageControl!
var cycelTimer : Timer? // 定时器隔断时间滚动广告栏
var cycleModel:[CyceleModel]?{
didSet{
// 刷新colletionView
collectionView.reloadData()
// 设置 pagecontrollr 的个数
pagecontrollr.numberOfPages = cycleModel?.count ?? 0
// 默认滚动到中间某一个位置
let indexPath = NSIndexPath(item: (cycleModel?.count ?? 0) * 10, section: 0)
collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false)
// 先移除定时器 后添加
RemoveCycleTimer()
addCycelTime()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// 该控件不随着父空间的拉伸而拉伸
collectionView.register(UINib(nibName: "CollectionViewCycelCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID)
}
override func layoutSubviews() {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.isPagingEnabled = true
}
}
// 提供快速创建view的类方法
extension RecommendCycleView{
class func RecommendCycleViewCustom()->RecommendCycleView{
return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView
}
}
// 遵守collectonView dataasource
extension RecommendCycleView:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModel?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionViewCycelCell
let cycleModelsingel = cycleModel?[indexPath.row % (cycleModel?.count)!]
cell.cycleModel = cycleModelsingel
return cell
}
}
// 遵守collectonView Delegate
extension RecommendCycleView:UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//1. 获取滚动的偏移量
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
//2。计算pagecontroller currentIndex
pagecontrollr.currentPage = Int(offsetX/scrollView.bounds.width) % (cycleModel?.count ?? 1)
}
// 用户拖拽的时候先移除定时器
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
RemoveCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycelTime()
}
}
// mark 定时器的操作方法
extension RecommendCycleView{
fileprivate func addCycelTime(){
cycelTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycelTimer!, forMode: .commonModes)
}
fileprivate func RemoveCycleTimer(){
// 从运行中移除定时器
cycelTimer?.invalidate()
cycelTimer = nil
}
@objc private func scrollToNext(){
// 1.获取滚动的偏移量
let currOffset = collectionView.contentOffset.x
let offset = currOffset + collectionView.bounds.width
// 2.滚动该位置
collectionView.setContentOffset(CGPoint(x: offset, y: 0), animated: true)
}
}
|
mit
|
8360c0ddcaddf055ea248c0d12fbd653
| 27.147887 | 132 | 0.643983 | 5.117798 | false | false | false | false |
nolili/FireFly
|
FireFly/ViewController.swift
|
1
|
2052
|
//
// ViewController.swift
// FireFly
//
// Created by nori on 2014/06/25.
//
//
import UIKit
import CoreLocation
let beaconUuid = NSUUID(UUIDString: "31840078-6F1B-448B-A6A2-CADA828E287D")
class ViewController: UIViewController ,CLLocationManagerDelegate{
// var locationManager:ImplicitlyUnwrappedOptionalType<CLLocationManager>
// var locationManager:Optional<CLLocationManager> ...nilがはいってるかも?型
var locationManager:CLLocationManager
init(coder aDecoder: NSCoder!) {
locationManager = CLLocationManager()
super.init(coder: aDecoder)
locationManager.delegate = self;
let beaconRegion = CLBeaconRegion(proximityUUID: beaconUuid, identifier:"hoge")
locationManager.startRangingBeaconsInRegion(beaconRegion)
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.startUpdatingLocation()
// 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.
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: AnyObject[]!, inRegion region: CLBeaconRegion!){
let maxDistance:CGFloat = 1.0
var proximity:CGFloat = 0.0
let beaconArray = beacons as CLBeacon[]
for beacon in beacons as CLBeacon[]{
println(beacon)
}
if (beacons.count > 0){
let nearestBeacon = beaconArray[0]
if (nearestBeacon.proximity != .Unknown){
proximity = CGFloat(nearestBeacon.accuracy)
if (proximity > maxDistance){
proximity = maxDistance;
}
let brightness:CGFloat = 1.0 - (proximity / maxDistance)
println(brightness)
UIScreen.mainScreen().brightness = brightness
}
}
}
}
|
mit
|
07d8192130dfcb014b378cb24d60429e
| 30.75 | 127 | 0.630413 | 5.347368 | false | false | false | false |
swiftingio/architecture-wars-mvc
|
MyCards/MyCards/CloseButton.swift
|
1
|
1232
|
//
// CloseButton.swift
// MyCards
//
// Created by Maciej Piotrowski on 23/11/16.
//
import UIKit
class CloseButton: TappableView {
let cross: UIView = UIView(frame: .zero).with {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = .white
}
override var bounds: CGRect {
didSet {
setCrossShape()
}
}
override var frame: CGRect {
didSet {
setCrossShape()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(cross)
NSLayoutConstraint.activate(NSLayoutConstraint.filledInSuperview(cross))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.height/2
}
func setCrossShape() {
let rect = bounds
let crossShape = CAShapeLayer()
crossShape.path = rect.crossPath
crossShape.strokeColor = UIColor.white.cgColor
crossShape.lineWidth = 2.0
crossShape.cornerRadius = rect.height/2.0
cross.layer.mask = crossShape
}
}
|
mit
|
1bca4903e7722a637cfc67d8e78b0239
| 22.245283 | 80 | 0.616883 | 4.463768 | false | false | false | false |
DenHeadless/DTCollectionViewManager
|
Sources/Tests/DiffableDatasourcesTestCase.swift
|
1
|
10681
|
//
// DiffableDatasourcesTestCase.swift
// DTCollectionViewManager
//
// Created by Denys Telezhkin on 7/30/19.
// Copyright © 2019 Denys Telezhkin. All rights reserved.
//
import XCTest
@testable import DTCollectionViewManager
@available(iOS 13, tvOS 13, *)
extension NSDiffableDataSourceSnapshot {
static func snapshot(with block: (inout NSDiffableDataSourceSnapshot<SectionIdentifierType, ItemIdentifierType>) -> ()) -> NSDiffableDataSourceSnapshot {
var snapshot = NSDiffableDataSourceSnapshot<SectionIdentifierType, ItemIdentifierType>()
block(&snapshot)
return snapshot
}
}
@available(iOS 13, tvOS 13, *)
extension NSDiffableDataSourceSnapshotReference {
static func snapshot(with block: (NSDiffableDataSourceSnapshotReference) -> ()) -> NSDiffableDataSourceSnapshotReference {
let snapshot = NSDiffableDataSourceSnapshotReference()
block(snapshot)
return snapshot
}
}
class DiffableDatasourcesTestCase: XCTestCase {
enum Section {
case one
case two
case three
}
var diffableDataSource: Any?
@available(iOS 13, tvOS 13, *)
var dataSource: UICollectionViewDiffableDataSource<Section, Int>! {
return diffableDataSource as? UICollectionViewDiffableDataSource<Section, Int>
}
var controller = DTCellTestCollectionController()
@available(iOS 13, tvOS 13, *)
func setItems(_ items: [Int]) {
dataSource.apply(.snapshot(with: { snapshot in
snapshot.appendSections([.one])
snapshot.appendItems(items)
}))
}
override func setUp() {
super.setUp()
guard #available(iOS 13, tvOS 13, *) else { return }
let _ = controller.view
let temp : UICollectionViewDiffableDataSource<Section, Int> = controller.manager.configureDiffableDataSource(modelProvider: { $1 })
diffableDataSource = temp
controller.manager.register(NibCell.self)
}
func testMultipleSectionsWorkWithDiffableDataSources() {
guard #available(iOS 13, tvOS 13, *) else { return }
dataSource.apply(.snapshot(with: { snapshot in
snapshot.appendSections([.one, .two])
snapshot.appendItems([1,2], toSection: .one)
snapshot.appendItems([3,4], toSection: .two)
}))
XCTAssert(controller.verifyItem(2, atIndexPath: indexPath(1, 0)))
XCTAssert(controller.verifyItem(3, atIndexPath: indexPath(0, 1)))
XCTAssertEqual(controller.manager.storage.numberOfSections(), 2)
XCTAssertEqual(controller.manager.storage.numberOfItems(inSection: 0), 2)
XCTAssertEqual(controller.manager.storage.numberOfItems(inSection: 1), 2)
}
func testCellSelectionClosure() throws
{
guard #available(iOS 13, tvOS 13, *) else { return }
if #available(iOS 15, tvOS 15, *) {
throw XCTSkip("This test fails on iOS 15 / tvOS 15 due to diffable datasources, that refuse to update cells if collection view is not on screen")
}
controller = ReactingTestCollectionViewController()
let _ = controller.view
let temp: UICollectionViewDiffableDataSource<Section, Int> = controller.manager.configureDiffableDataSource(modelProvider: { $1 })
diffableDataSource = temp
controller.manager.register(SelectionReactingCollectionCell.self)
var reactingCell : SelectionReactingCollectionCell?
controller.manager.didSelect(SelectionReactingCollectionCell.self) { (cell, model, indexPath) in
cell.indexPath = indexPath
cell.model = model
reactingCell = cell
}
dataSource.apply(.snapshot(with: { snapshot in
snapshot.appendSections([.one])
snapshot.appendItems([1,2], toSection: .one)
}))
controller.manager.collectionDelegate?.collectionView(controller.collectionView, didSelectItemAt: indexPath(1, 0))
XCTAssertEqual(reactingCell?.indexPath, indexPath(1, 0))
XCTAssertEqual(reactingCell?.model, 2)
}
func testShouldShowViewHeaderOnEmptySEction()
{
guard #available(iOS 13, tvOS 13, *) else { return }
controller.manager.registerHeader(NibHeaderFooterView.self)
controller.manager.supplementaryStorage?.setSectionHeaderModels([1])
setItems([])
XCTAssertNotNil(controller.manager.collectionDataSource?.collectionView(controller.collectionView,
viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader,
at: indexPath(0, 0)))
}
func testShouldShowViewFooterOnEmptySection()
{
guard #available(iOS 13, tvOS 13, *) else { return }
controller.manager.registerFooter(NibHeaderFooterView.self)
controller.manager.supplementaryStorage?.setSectionFooterModels([1])
setItems([])
XCTAssertNotNil(controller.manager.collectionDataSource?.collectionView(controller.collectionView,
viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionFooter,
at: indexPath(0, 0)))
}
func testSupplementaryKindsShouldBeSet()
{
XCTAssertEqual(controller.manager.supplementaryStorage?.supplementaryHeaderKind, UICollectionView.elementKindSectionHeader)
XCTAssertEqual(controller.manager.supplementaryStorage?.supplementaryFooterKind, UICollectionView.elementKindSectionFooter)
}
func testHeaderViewShouldBeCreated()
{
guard #available(iOS 13, tvOS 13, *) else { return }
controller.manager.registerHeader(NibHeaderFooterView.self)
controller.manager.supplementaryStorage?.setSectionHeaderModels([1])
setItems([1])
XCTAssert(controller.manager.collectionDataSource?.collectionView(controller.collectionView,
viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader,
at: indexPath(0, 0)) is NibHeaderFooterView)
}
func testFooterViewShouldBeCreated()
{
guard #available(iOS 13, tvOS 13, *) else { return }
controller.manager.registerFooter(NibHeaderFooterView.self)
controller.manager.supplementaryStorage?.setSectionFooterModels([1])
setItems([1])
XCTAssert(controller.manager.collectionDataSource?.collectionView(controller.collectionView,
viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionFooter,
at: indexPath(0, 0)) is NibHeaderFooterView)
}
func testHeaderViewShouldBeCreatedFromXib()
{
guard #available(iOS 13, tvOS 13, *) else { return }
controller.manager.registerHeader(NibHeaderFooterView.self) { mapping in
mapping.xibName = "NibHeaderFooterView"
}
controller.manager.supplementaryStorage?.setSectionHeaderModels([1])
setItems([1])
XCTAssert(controller.manager.collectionDataSource?.collectionView(controller.collectionView,
viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader,
at: indexPath(0, 0)) is NibHeaderFooterView)
}
func testFooterViewShouldBeCreatedFromXib()
{
guard #available(iOS 13, tvOS 13, *) else { return }
controller.manager.registerFooter(NibHeaderFooterView.self) { mapping in
mapping.xibName = "NibHeaderFooterView"
}
controller.manager.supplementaryStorage?.setSectionFooterModels([1])
setItems([1])
XCTAssert(controller.manager.collectionDataSource?.collectionView(controller.collectionView,
viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionFooter,
at: indexPath(0, 0)) is NibHeaderFooterView)
}
func testWillDisplayHeaderInSection() {
guard #available(iOS 13, tvOS 13, *) else { return }
let exp = expectation(description: "willDisplayHeaderInSection")
controller.manager.registerHeader(ReactingHeaderFooterView.self)
controller.manager.willDisplayHeaderView(ReactingHeaderFooterView.self, { header, model, section in
exp.fulfill()
})
controller.manager.supplementaryStorage?.setSectionHeaderModels(["Foo"])
setItems([])
_ = controller.manager.collectionDelegate?.collectionView(controller.collectionView,
willDisplaySupplementaryView: ReactingHeaderFooterView(),
forElementKind: UICollectionView.elementKindSectionHeader,
at: indexPath(0, 0))
waitForExpectations(timeout: 1, handler: nil)
}
func testWillDisplayFooterInSection() {
guard #available(iOS 13, tvOS 13, *) else { return }
let exp = expectation(description: "willDisplayFooterInSection")
controller.manager.registerFooter(ReactingHeaderFooterView.self)
controller.manager.willDisplayFooterView(ReactingHeaderFooterView.self, { footer, model, section in
exp.fulfill()
})
controller.manager.supplementaryStorage?.setSectionFooterModels(["Foo"])
setItems([])
_ = controller.manager.collectionDelegate?.collectionView(controller.collectionView,
willDisplaySupplementaryView: ReactingHeaderFooterView(),
forElementKind: UICollectionView.elementKindSectionFooter,
at: indexPath(0, 0))
waitForExpectations(timeout: 1, handler: nil)
}
}
|
mit
|
6fcf1b694f736ede7cfde59ac365f89a
| 49.857143 | 170 | 0.61573 | 6.102857 | false | true | false | false |
tjw/swift
|
test/decl/init/nil.swift
|
1
|
1395
|
// RUN: %target-typecheck-verify-swift
var a: Int = nil
// expected-error@-1 {{nil cannot initialize specified type 'Int'}}
// expected-note@-2 {{add '?' to form the optional type 'Int?'}} {{11-11=?}}
var b: () -> Void = nil
// expected-error@-1 {{nil cannot initialize specified type '() -> Void'}}
// expected-note@-2 {{add '?' to form the optional type '(() -> Void)?'}} {{8-8=(}} {{18-18=)?}}
var c, d: Int = nil
// expected-error@-1 {{type annotation missing in pattern}}
// expected-error@-2 {{nil cannot initialize specified type 'Int'}}
// expected-note@-3 {{add '?' to form the optional type 'Int?'}} {{14-14=?}}
var (e, f): (Int, Int) = nil
// expected-error@-1 {{nil cannot initialize specified type '(Int, Int)'}}
var g: Int = nil, h: Int = nil
// expected-error@-1 {{nil cannot initialize specified type 'Int'}}
// expected-note@-2 {{add '?' to form the optional type 'Int?'}} {{11-11=?}}
// expected-error@-3 {{nil cannot initialize specified type 'Int'}}
// expected-note@-4 {{add '?' to form the optional type 'Int?'}} {{25-25=?}}
var _: Int = nil
// expected-error@-1 {{nil cannot initialize specified type 'Int'}}
// expected-note@-2 {{add '?' to form the optional type 'Int?'}} {{11-11=?}}
// 'nil' can initialize the specified type, if its generic parameters are bound
var _: Array? = nil // expected-error {{generic parameter 'Element' could not be inferred}}
|
apache-2.0
|
42e61d9740999ea80811044240dfbe5f
| 45.5 | 96 | 0.635125 | 3.522727 | false | false | false | false |
caiomello/utilities
|
Sources/Utilities/Protocols & Classes/PaginatedList.swift
|
1
|
641
|
//
// PaginatedList.swift
// Utilities
//
// Created by Caio Mello on 7/5/19.
// Copyright © 2019 Caio Mello. All rights reserved.
//
import Foundation
public protocol PaginatedList {
var page: Int { get set }
func requestPage(_ page: Int)
}
extension PaginatedList {
public func requestNextPageIfNeeded(currentIndex: Int, itemsPerPage: Int, initialPage: Int, offset: Int = 0) {
let currentPage = initialPage == 0 ? page + 1 : page
let lastIndexInCurrentPage = itemsPerPage * currentPage
if currentIndex == (lastIndexInCurrentPage - offset) {
requestPage(page + 1)
}
}
}
|
mit
|
108a458af26d1e7931798529bfb433bb
| 23.615385 | 114 | 0.657813 | 3.92638 | false | false | false | false |
RylynnLai/V2EX_sf
|
V2EX/View/RLNodeTopicCell.swift
|
1
|
1507
|
//
// RLNodeTopicCell.swift
// V2EX
//
// Created by LLZ on 16/5/12.
// Copyright © 2016年 LLZ. All rights reserved.
//
import UIKit
class RLNodeTopicCell: UITableViewCell {
var topicModel:Topic? {
didSet{
titleLable.text = topicModel?.title
//以下两项没数据就空白
contentLable.text = topicModel?.content
//-------------------------------------------------
let iconURL = NSURL.init(string: "http:\(topicModel!.member!.avatar_normal ?? "")")
authorBtn.sd_setBackgroundImageWithURL(iconURL, forState: .Normal, placeholderImage: UIImage.init(named: "blank"))
replieNumLable.text = topicModel?.replies?.stringValue
}
}
@IBOutlet weak var titleLable: UILabel!
@IBOutlet weak var contentLable: UILabel!
@IBOutlet weak var authorBtn: UIButton!
@IBOutlet weak var replieNumLable: UILabel!
@IBOutlet weak var bgView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
authorBtn.layer.cornerRadius = authorBtn.bounds.size.height * 0.5
authorBtn.layer.masksToBounds = true
replieNumLable.layer.cornerRadius = replieNumLable.bounds.size.height * 0.5
replieNumLable.layer.masksToBounds = true
bgView.layer.cornerRadius = 10
bgView.layer.masksToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
mit
|
254fa19e02c197e4b63ec5618c9e275d
| 31.977778 | 126 | 0.634097 | 4.301449 | false | false | false | false |
andrzejsemeniuk/ASToolkit
|
ASToolkit/UIViewPile.swift
|
1
|
1337
|
//
// UIViewPile.swift
// ASToolkit
//
// Created by andrzej semeniuk on 8/17/17.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import Foundation
open class UIViewPile : UIView {
public init(frame:CGRect, pile:[UIView]) {
super.init(frame:CGRect(pile[0].frame.size))
self.backgroundColor = .clear
add(views:pile)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func add(views:[UIView]) {
var top = self.top()
for view in views {
top.addSubview(view)
view.constrainCenterToSuperview()
top = view
}
}
public func top() -> UIView {
var result:UIView = self
while let last = result.subviews.last {
result = last
}
return result
}
public func nextUp() -> UIView? {
return subviews.last
}
public func nextDown() -> UIView? {
return superview
}
}
open class UIViewPileCentered : UIViewPile {
override public func add(views:[UIView]) {
var top = self.top()
for view in views {
top.addSubview(view)
view.constrainCenterToSuperview()
top = view
}
}
}
|
mit
|
14b837a4399fd5852bf743d073bcd9e6
| 21.266667 | 59 | 0.556886 | 4.254777 | false | false | false | false |
keyeMyria/edx-app-ios
|
Source/NSAttributedString+Combination.swift
|
2
|
855
|
//
// NSAttributedString+Combination.swift
// edX
//
// Created by Akiva Leffert on 6/22/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
extension NSAttributedString {
class func joinInNaturalLayout(var attributedStrings : [NSAttributedString]) -> NSAttributedString {
if UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft {
attributedStrings = attributedStrings.reverse()
}
let blankSpace = NSAttributedString(string : " ")
var resultString = NSMutableAttributedString()
for (index,attrString) in enumerate(attributedStrings) {
if index != 0 { resultString.appendAttributedString(blankSpace) }
resultString.appendAttributedString(attrString)
}
return resultString
}
}
|
apache-2.0
|
024ef7603623f97186c91b716c620585
| 29.535714 | 104 | 0.666667 | 5.662252 | false | false | false | false |
lexrus/LTMorphingLabel
|
LTMorphingLabel/LTMorphingLabel+Fall.swift
|
2
|
5732
|
//
// LTMorphingLabel+Fall.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2017 Lex Tang, http://lexrus.com
//
// 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
extension LTMorphingLabel {
@objc
func FallLoad() {
progressClosures["Fall\(LTMorphingPhases.progress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if isNewChar {
return min(
1.0,
max(
0.0,
progress
- self.morphingCharacterDelay
* Float(index)
/ 1.7
)
)
}
let j: Float = Float(sin(Double(index))) * 1.7
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * Float(j)))
}
effectClosures["Fall\(LTMorphingPhases.disappear)"] = {
char, index, progress in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress))
}
effectClosures["Fall\(LTMorphingPhases.appear)"] = {
char, index, progress in
let currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0.0, Float(self.font.pointSize))
)
let yOffset = CGFloat(self.font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: self.newRects[index].offsetBy(dx: 0, dy: yOffset),
alpha: CGFloat(self.morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
drawingClosures["Fall\(LTMorphingPhases.draw)"] = {
limbo in
if limbo.drawingProgress > 0.0 {
let context = UIGraphicsGetCurrentContext()
var charRect = limbo.rect
context!.saveGState()
let charCenterX = charRect.origin.x + (charRect.size.width / 2.0)
var charBottomY = charRect.origin.y + charRect.size.height - self.font.pointSize / 6
var charColor: UIColor = self.textColor
// Fall down if drawingProgress is more than 50%
if limbo.drawingProgress > 0.5 {
let ease = CGFloat(
LTEasing.easeInQuint(
Float(limbo.drawingProgress - 0.4),
0.0,
1.0,
0.5
)
)
charBottomY += ease * 10.0
let fadeOutAlpha = min(
1.0,
max(
0.0,
limbo.drawingProgress * -2.0 + 2.0 + 0.01
)
)
charColor = self.textColor.withAlphaComponent(fadeOutAlpha)
}
charRect = CGRect(
x: charRect.size.width / -2.0,
y: charRect.size.height * -1.0 + self.font.pointSize / 6,
width: charRect.size.width,
height: charRect.size.height)
context!.translateBy(x: charCenterX, y: charBottomY)
let angle = Float(sin(Double(limbo.rect.origin.x)) > 0.5 ? 168 : -168)
let rotation = CGFloat(
LTEasing.easeOutBack(
min(
1.0,
Float(limbo.drawingProgress)
),
0.0,
1.0
) * angle
)
context!.rotate(by: rotation * CGFloat(Double.pi) / 180.0)
let s = String(limbo.char)
let attributes: [NSAttributedString.Key: Any] = [
.font: self.font.withSize(limbo.size),
.foregroundColor: charColor
]
s.draw(in: charRect, withAttributes: attributes)
context!.restoreGState()
return true
}
return false
}
}
}
|
mit
|
ce7779356563d2f9933d6b9fe7e3c2ac
| 37.16 | 100 | 0.488295 | 5.295097 | false | false | false | false |
polkahq/PLKSwift
|
Sources/polka/utils/PLKMacros.swift
|
1
|
1136
|
//
// PLKMacros.swift
//
// Created by Alvaro Talavera on 5/11/16.
// Copyright © 2016 Polka. All rights reserved.
//
import UIKit
public struct PLKScreenSize
{
public static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
public static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
public static let SCREEN_MAX_LENGTH = max(PLKScreenSize.SCREEN_WIDTH, PLKScreenSize.SCREEN_HEIGHT)
public static let SCREEN_MIN_LENGTH = min(PLKScreenSize.SCREEN_WIDTH, PLKScreenSize.SCREEN_HEIGHT)
}
public struct PLKDeviceType
{
public static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && PLKScreenSize.SCREEN_MAX_LENGTH < 568.0
public static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && PLKScreenSize.SCREEN_MAX_LENGTH == 568.0
public static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && PLKScreenSize.SCREEN_MAX_LENGTH == 667.0
public static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && PLKScreenSize.SCREEN_MAX_LENGTH == 736.0
public static let IS_PAD = UIDevice.current.userInterfaceIdiom == .pad
}
|
mit
|
e09e658f25cfa0b62971047c24b67b78
| 44.4 | 133 | 0.74978 | 3.770764 | false | false | false | false |
vhesener/Closures
|
Xcode/Closures/Source/UICollectionView.swift
|
2
|
42609
|
/**
The MIT License (MIT)
Copyright (c) 2017 Vincent Hesener
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
/// :nodoc:
private let jzyBug = 0 // Prevent the license header from showing up in Jazzy Docs for UICollectionView
@available(iOS 9.0, *)
extension UICollectionView {
// MARK: Common Array Usage
/**
This method defaults many of the boilerplate callbacks needed to populate a
UICollectionView when using an `Array` as a data source.
The defaults that this method takes care of:
* Registers the cell's class and reuse identifier with a default value
* Optionally uses a cellNibName value to create the cell from a nib file
from the main bundle
* Handles cell dequeueing and provides a reference to the cell
in the `item` closure for you to modify in place.
* Provides the number of sections
* Provides the number of items
This method simply sets basic default behavior. This means that you can
override the default collection view handlers after this method is called.
However, remember that order matters. If you call this method after you
override the `numberOfSectionsIn` callback, for instance, the closure
you passed into `numberOfSectionsIn` will be wiped out by this method
and you will have to override that closure handler again.
* Important:
Please remember that Swift `Array`s are value types. This means that they
are copied when mutaded. When the values or sequence of your array changes, you will
need to call this method again, just before you
call reloadData(). If you have a lot of collection view customization in addtion to a lot
of updates to your array, it is more appropriate to use the individual
closure handlers instead of this method.
* * * *
#### An example of calling this method:
```swift
collectionView.addFlowElements(<#myArray#>, cell: <#MyUICollectionViewCellClass#>) { element, cell, index in
cell.imageView.image = <#T##someImage(from: element)##UIImage#>
}
```
* parameter array: An Array to be used for each item.
* parameter cell: A type of cell to use when calling `dequeueReusableCell(withReuseIdentifier:for:)`
* parameter cellNibName: If non-nil, the cell will be dequeued using a nib with this name from the main bundle
* parameter item: A closure that's called when a cell is about to be shown and needs to be configured.
* returns: itself so you can daisy chain the other datasource calls
*/
@discardableResult
public func addFlowElements<Element,Cell>(
_ elements: [Element],
cell: Cell.Type,
cellNibName: String? = nil,
item: @escaping (_ element: Element, _ cell: inout Cell,_ index: Int) -> Void) -> Self
where Cell: UICollectionViewCell {
return _addSections([elements], cell: cell, cellNibName: cellNibName, item: item)
}
@discardableResult
private func _addSections<Element,Cell>(
_ elements: [[Element]],
cell: Cell.Type,
cellNibName: String? = nil,
item: @escaping (_ element: Element, _ cell: inout Cell,_ index: Int) -> Void) -> Self
where Cell: UICollectionViewCell {
DelegateWrapper.remove(delegator: self, from: &CollectionViewDelegate.delegates)
delegate = nil
dataSource = nil
let reuseIdentifier = "\(Element.self).\(cell)"
if let nibName = cellNibName {
register(UINib(nibName: nibName, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
} else {
register(Cell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
return numberOfSectionsIn
{
return elements.count
}.numberOfItemsInSection {
return elements[$0].count
}.cellForItemAt { [unowned self] in
let element = elements[$0.section][$0.item]
var cell = self.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: $0) as! Cell
item(element, &cell, $0.item)
return cell
}
}
}
@available(iOS 9.0, *)
class CollectionViewDelegate: ScrollViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
fileprivate static var delegates = Set<DelegateWrapper<UICollectionView, CollectionViewDelegate>>()
fileprivate var shouldHighlightItemAt: ((_ indexPath: IndexPath) -> Bool)?
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return shouldHighlightItemAt?(indexPath) ?? true
}
fileprivate var didHighlightItemAt: ((_ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
didHighlightItemAt?(indexPath)
}
fileprivate var didUnhighlightItemAt: ((_ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
didUnhighlightItemAt?(indexPath)
}
fileprivate var shouldSelectItemAt: ((_ indexPath: IndexPath) -> Bool)?
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return shouldSelectItemAt?(indexPath) ?? true
}
fileprivate var shouldDeselectItemAt: ((_ indexPath: IndexPath) -> Bool)?
func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
return shouldDeselectItemAt?(indexPath) ?? true
}
fileprivate var didSelectItemAt: ((_ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didSelectItemAt?(indexPath)
}
fileprivate var didDeselectItemAt: ((_ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
didDeselectItemAt?(indexPath)
}
fileprivate var willDisplay: ((_ cell: UICollectionViewCell, _ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
willDisplay?(cell,indexPath)
}
fileprivate var willDisplaySupplementaryView: ((_ elementKind: String, _ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
willDisplaySupplementaryView?(elementKind,indexPath)
}
fileprivate var didEndDisplaying: ((_ cell: UICollectionViewCell, _ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
didEndDisplaying?(cell,indexPath)
}
fileprivate var didEndDisplayingSupplementaryView: ((_ elementKind: String, _ indexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
didEndDisplayingSupplementaryView?(elementKind,indexPath)
}
fileprivate var shouldShowMenuForItemAt: ((_ indexPath: IndexPath) -> Bool)?
func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return shouldShowMenuForItemAt?(indexPath) ?? false
}
fileprivate var canPerformAction: ((_ action: Selector, _ indexPath: IndexPath, _ sender: Any?) -> Bool)?
func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return canPerformAction?(action, indexPath, sender) ?? false
}
fileprivate var performAction: ((_ action: Selector, _ indexPath: IndexPath, _ sender: Any?) -> Void)?
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
performAction?(action, indexPath, sender)
}
fileprivate var transitionLayoutForOldLayout: ((_ fromLayout: UICollectionViewLayout, _ toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout)?
func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
return transitionLayoutForOldLayout?(fromLayout,toLayout) ?? UICollectionViewTransitionLayout(currentLayout: fromLayout, nextLayout: toLayout)
}
fileprivate var canFocusItemAt: ((_ indexPath: IndexPath) -> Bool)?
func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool {
return canFocusItemAt?(indexPath) ?? false
}
fileprivate var shouldUpdateFocusIn: ((_ context: UICollectionViewFocusUpdateContext) -> Bool)?
func collectionView(_ collectionView: UICollectionView, shouldUpdateFocusIn context: UICollectionViewFocusUpdateContext) -> Bool {
return shouldUpdateFocusIn?(context) ?? true
}
fileprivate var didUpdateFocusIn: ((_ context: UICollectionViewFocusUpdateContext, _ coordinator: UIFocusAnimationCoordinator) -> Void)?
func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
didUpdateFocusIn?(context,coordinator)
}
fileprivate var indexPathForPreferredFocusedViewIn: (() -> IndexPath?)?
func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? {
return indexPathForPreferredFocusedViewIn?() ?? nil
}
fileprivate var targetIndexPathForMoveFromItemAt: ((_ originalIndexPath: IndexPath, _ proposedIndexPath: IndexPath) -> IndexPath)?
func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
return targetIndexPathForMoveFromItemAt?(originalIndexPath,proposedIndexPath) ?? proposedIndexPath
}
fileprivate var targetContentOffsetForProposedContentOffset: ((_ proposedContentOffset: CGPoint) -> CGPoint)?
func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return targetContentOffsetForProposedContentOffset?(proposedContentOffset) ?? proposedContentOffset
}
private var _shouldSpringLoadItemAt: Any?
@available(iOS 11, *)
fileprivate var shouldSpringLoadItemAt: ((_ indexPath: IndexPath, _ context: UISpringLoadedInteractionContext) -> Bool)? {
get {
return _shouldSpringLoadItemAt as? (_ indexPath: IndexPath, _ context: UISpringLoadedInteractionContext) -> Bool
}
set {
_shouldSpringLoadItemAt = newValue
}
}
@available(iOS 11, *)
func collectionView(_ collectionView: UICollectionView, shouldSpringLoadItemAt indexPath: IndexPath, with context: UISpringLoadedInteractionContext) -> Bool {
return shouldSpringLoadItemAt?(indexPath, context) ?? true
}
fileprivate var numberOfItemsInSection: ((_ section: Int) -> Int)?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItemsInSection?(section) ?? 0
}
fileprivate var cellForItemAt: ((_ indexPath: IndexPath) -> UICollectionViewCell)?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return cellForItemAt?(indexPath) ?? UICollectionViewCell()
}
fileprivate var numberOfSectionsIn: (() -> Int)?
func numberOfSections(in collectionView: UICollectionView) -> Int {
return numberOfSectionsIn?() ?? 1
}
fileprivate var viewForSupplementaryElementOfKind: ((_ kind: String, _ indexPath: IndexPath) -> UICollectionReusableView)?
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return viewForSupplementaryElementOfKind?(kind,indexPath) ?? UICollectionReusableView()
}
fileprivate var canMoveItemAt: ((_ indexPath: IndexPath) -> Bool)?
func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return canMoveItemAt?(indexPath) ?? false
}
fileprivate var moveItemAt: ((_ sourceIndexPath: IndexPath, _ destinationIndexPath: IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
moveItemAt?(sourceIndexPath,destinationIndexPath)
}
fileprivate var indexTitlesFor: (() -> [String])?
func indexTitles(for collectionView: UICollectionView) -> [String]? {
return indexTitlesFor?() ?? []
}
fileprivate var indexPathForIndexTitle: ((_ title: String, _ index: Int) -> IndexPath)?
func collectionView(_ collectionView: UICollectionView, indexPathForIndexTitle title: String, at index: Int) -> IndexPath {
return indexPathForIndexTitle?(title,index) ?? IndexPath()
}
fileprivate var sizeForItemAt: ((_ indexPath: IndexPath) -> CGSize)?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return sizeForItemAt?(indexPath) ?? (collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize ?? CGSize(width: 50, height: 50)
}
fileprivate var insetForSectionAt: ((_ section: Int) -> UIEdgeInsets)?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return insetForSectionAt?(section) ?? (collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset ?? .zero
}
fileprivate var minimumLineSpacingForSectionAt: ((_ section: Int) -> CGFloat)?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return minimumLineSpacingForSectionAt?(section) ?? (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumLineSpacing ?? 10
}
fileprivate var minimumInteritemSpacingForSectionAt: ((_ section: Int) -> CGFloat)?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return minimumInteritemSpacingForSectionAt?(section) ?? (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumInteritemSpacing ?? 10
}
fileprivate var referenceSizeForHeaderInSection: ((_ section: Int) -> CGSize)?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return referenceSizeForHeaderInSection?(section) ?? (collectionViewLayout as? UICollectionViewFlowLayout)?.headerReferenceSize ?? .zero
}
fileprivate var referenceSizeForFooterInSection: ((_ section: Int) -> CGSize)?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return referenceSizeForFooterInSection?(section) ?? (collectionViewLayout as? UICollectionViewFlowLayout)?.footerReferenceSize ?? .zero
}
override func responds(to aSelector: Selector!) -> Bool {
if #available(iOS 11, *) {
switch aSelector {
case #selector(CollectionViewDelegate.collectionView(_:shouldSpringLoadItemAt:with:)):
return _shouldSpringLoadItemAt != nil
default:
break
}
}
switch aSelector {
case #selector(CollectionViewDelegate.collectionView(_:shouldHighlightItemAt:)):
return shouldHighlightItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:didHighlightItemAt:)):
return didHighlightItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:didUnhighlightItemAt:)):
return didUnhighlightItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:shouldSelectItemAt:)):
return shouldSelectItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:shouldDeselectItemAt:)):
return shouldDeselectItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:didSelectItemAt:)):
return didSelectItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:didDeselectItemAt:)):
return didDeselectItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:willDisplay:forItemAt:)):
return willDisplay != nil
case #selector(CollectionViewDelegate.collectionView(_:willDisplaySupplementaryView:forElementKind:at:)):
return willDisplaySupplementaryView != nil
case #selector(CollectionViewDelegate.collectionView(_:didEndDisplaying:forItemAt:)):
return didEndDisplaying != nil
case #selector(CollectionViewDelegate.collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:)):
return didEndDisplayingSupplementaryView != nil
case #selector(CollectionViewDelegate.collectionView(_:shouldShowMenuForItemAt:)):
return shouldShowMenuForItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:canPerformAction:forItemAt:withSender:)):
return canPerformAction != nil
case #selector(CollectionViewDelegate.collectionView(_:performAction:forItemAt:withSender:)):
return performAction != nil
case #selector(CollectionViewDelegate.collectionView(_:transitionLayoutForOldLayout:newLayout:)):
return transitionLayoutForOldLayout != nil
case #selector(CollectionViewDelegate.collectionView(_:canFocusItemAt:)):
return canFocusItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:shouldUpdateFocusIn:)):
return shouldUpdateFocusIn != nil
case #selector(CollectionViewDelegate.collectionView(_:didUpdateFocusIn:with:)):
return didUpdateFocusIn != nil
case #selector(CollectionViewDelegate.indexPathForPreferredFocusedView(in:)):
return indexPathForPreferredFocusedViewIn != nil
case #selector(CollectionViewDelegate.collectionView(_:targetIndexPathForMoveFromItemAt:toProposedIndexPath:)):
return targetIndexPathForMoveFromItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:targetContentOffsetForProposedContentOffset:)):
return targetContentOffsetForProposedContentOffset != nil
case #selector(CollectionViewDelegate.collectionView(_:numberOfItemsInSection:)):
return numberOfItemsInSection != nil
case #selector(CollectionViewDelegate.collectionView(_:cellForItemAt:)):
return cellForItemAt != nil
case #selector(CollectionViewDelegate.numberOfSections(in:)):
return numberOfSectionsIn != nil
case #selector(CollectionViewDelegate.collectionView(_:viewForSupplementaryElementOfKind:at:)):
return viewForSupplementaryElementOfKind != nil
case #selector(CollectionViewDelegate.collectionView(_:canMoveItemAt:)):
return canMoveItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:moveItemAt:to:)):
return moveItemAt != nil
case #selector(CollectionViewDelegate.indexTitles(for:)):
return indexTitlesFor != nil
case #selector(CollectionViewDelegate.collectionView(_:indexPathForIndexTitle:at:)):
return indexPathForIndexTitle != nil
case #selector(CollectionViewDelegate.collectionView(_:layout:sizeForItemAt:)):
return sizeForItemAt != nil
case #selector(CollectionViewDelegate.collectionView(_:layout:insetForSectionAt:)):
return insetForSectionAt != nil
case #selector(CollectionViewDelegate.collectionView(_:layout:minimumLineSpacingForSectionAt:)):
return minimumLineSpacingForSectionAt != nil
case #selector(CollectionViewDelegate.collectionView(_:layout:minimumInteritemSpacingForSectionAt:)):
return minimumInteritemSpacingForSectionAt != nil
case #selector(CollectionViewDelegate.collectionView(_:layout:referenceSizeForHeaderInSection:)):
return referenceSizeForHeaderInSection != nil
case #selector(CollectionViewDelegate.collectionView(_:layout:referenceSizeForFooterInSection:)):
return referenceSizeForFooterInSection != nil
default:
return super.responds(to: aSelector)
}
}
}
@available(iOS 9.0, *)
extension UICollectionView {
// MARK: Delegate and DataSource Overrides
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:shouldHighlightItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func shouldHighlightItemAt(handler: @escaping (_ indexPath: IndexPath) -> Bool) -> Self {
return update { $0.shouldHighlightItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:didHighlightItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func didHighlightItemAt(handler: @escaping (_ indexPath: IndexPath) -> Void) -> Self {
return update { $0.didHighlightItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:didUnhighlightItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func didUnhighlightItemAt(handler: @escaping (_ indexPath: IndexPath) -> Void) -> Self {
return update { $0.didUnhighlightItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:shouldSelectItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func shouldSelectItemAt(handler: @escaping (_ indexPath: IndexPath) -> Bool) -> Self {
return update { $0.shouldSelectItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:shouldDeselectItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func shouldDeselectItemAt(handler: @escaping (_ indexPath: IndexPath) -> Bool) -> Self {
return update { $0.shouldDeselectItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:didSelectItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func didSelectItemAt(handler: @escaping (_ indexPath: IndexPath) -> Void) -> Self {
return update { $0.didSelectItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:didDeselectItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func didDeselectItemAt(handler: @escaping (_ indexPath: IndexPath) -> Void) -> Self {
return update { $0.didDeselectItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:willDisplay:forItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func willDisplay(handler: @escaping (_ cell: UICollectionViewCell, _ indexPath: IndexPath) -> Void) -> Self {
return update { $0.willDisplay = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:willDisplaySupplementaryView:forElementKind:at:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func willDisplaySupplementaryView(handler: @escaping (_ elementKind: String, _ indexPath: IndexPath) -> Void) -> Self {
return update { $0.willDisplaySupplementaryView = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:didEndDisplaying:forItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func didEndDisplaying(handler: @escaping (_ cell: UICollectionViewCell, _ indexPath: IndexPath) -> Void) -> Self {
return update { $0.didEndDisplaying = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func didEndDisplayingSupplementaryView(handler: @escaping (_ elementKind: String, _ indexPath: IndexPath) -> Void) -> Self {
return update { $0.didEndDisplayingSupplementaryView = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:shouldShowMenuForItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func shouldShowMenuForItemAt(handler: @escaping (_ indexPath: IndexPath) -> Bool) -> Self {
return update { $0.shouldShowMenuForItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:canPerformAction:forItemAt:withSender:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func canPerformAction(handler: @escaping (_ action: Selector, _ indexPath: IndexPath, _ sender: Any?) -> Bool) -> Self {
return update { $0.canPerformAction = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:performAction:forItemAt:withSender:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func performAction(handler: @escaping (_ action: Selector, _ indexPath: IndexPath, _ sender: Any?) -> Void) -> Self {
return update { $0.performAction = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:transitionLayoutForOldLayout:newLayout:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func transitionLayoutForOldLayout(handler: @escaping (_ fromLayout: UICollectionViewLayout, _ toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout) -> Self {
return update { $0.transitionLayoutForOldLayout = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:canFocusItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func canFocusItemAt(handler: @escaping (_ indexPath: IndexPath) -> Bool) -> Self {
return update { $0.canFocusItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:shouldUpdateFocusIn:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func shouldUpdateFocusIn(handler: @escaping (_ context: UICollectionViewFocusUpdateContext) -> Bool) -> Self {
return update { $0.shouldUpdateFocusIn = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:didUpdateFocusIn:with:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func didUpdateFocusIn(handler: @escaping (_ context: UICollectionViewFocusUpdateContext, _ coordinator: UIFocusAnimationCoordinator) -> Void) -> Self {
return update { $0.didUpdateFocusIn = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's indexPathForPreferredFocusedVies(in:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func indexPathForPreferredFocusedViewIn(handler: @escaping () -> IndexPath?) -> Self {
return update { $0.indexPathForPreferredFocusedViewIn = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:targetIndexPathForMoveFromItemAt:toProposedIndexPath:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func targetIndexPathForMoveFromItemAt(handler: @escaping (_ originalIndexPath: IndexPath, _ proposedIndexPath: IndexPath) -> IndexPath) -> Self {
return update { $0.targetIndexPathForMoveFromItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:targetContentOffsetForProposedContentOffset:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func targetContentOffsetForProposedContentOffset(handler: @escaping (_ proposedContentOffset: CGPoint) -> CGPoint) -> Self {
return update { $0.targetContentOffsetForProposedContentOffset = handler }
}
/**
Equivalent to implementing UICollectionViewDelegate's collectionView(_:shouldSpringLoadItemAt:with:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@available(iOS 11, *) @discardableResult
public func shouldSpringLoadItemAt(handler: @escaping (_ indexPath: IndexPath, _ context: UISpringLoadedInteractionContext) -> Bool) -> Self {
return update { $0.shouldSpringLoadItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's collectionView(_:numberOfItemsInSection:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func numberOfItemsInSection(handler: @escaping (_ section: Int) -> Int) -> Self {
return update { $0.numberOfItemsInSection = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's collectionView(_:cellForItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func cellForItemAt(handler: @escaping (_ indexPath: IndexPath) -> UICollectionViewCell) -> Self {
return update { $0.cellForItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's numberOfSections(in:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func numberOfSectionsIn(handler: @escaping () -> Int) -> Self {
return update { $0.numberOfSectionsIn = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's collectionView(_:viewForSupplementaryElementOfKind:at:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func viewForSupplementaryElementOfKind(handler: @escaping (_ kind: String, _ indexPath: IndexPath) -> UICollectionReusableView) -> Self {
return update { $0.viewForSupplementaryElementOfKind = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's collectionView(_:canMoveItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func canMoveItemAt(handler: @escaping (_ indexPath: IndexPath) -> Bool) -> Self {
return update { $0.canMoveItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's collectionView(_:moveItemAt:to:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func moveItemAt(handler: @escaping (_ sourceIndexPath: IndexPath, _ destinationIndexPath: IndexPath) -> Void) -> Self {
return update { $0.moveItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's indexTitles(for:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func indexTitlesFor(handler: @escaping () -> [String]) -> Self {
return update { $0.indexTitlesFor = handler }
}
/**
Equivalent to implementing UICollectionViewDataSource's collectionView(_:indexPathForIndexTitle:at:) method
* parameter handler: The closure that will be called in place of its equivalent dataSource method
* returns: itself so you can daisy chain the other dataSource calls
*/
@discardableResult
public func indexPathForIndexTitle(handler: @escaping (_ title: String, _ index: Int) -> IndexPath) -> Self {
return update { $0.indexPathForIndexTitle = handler }
}
/**
Equivalent to implementing UICollectionViewDelegateFlowLayout's collectionView(_:layout:sizeForItemAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func sizeForItemAt(handler: @escaping (_ indexPath: IndexPath) -> CGSize) -> Self {
return update { $0.sizeForItemAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegateFlowLayout's collectionV(_:layout:insetForSectionAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func insetForSectionAt(handler: @escaping (_ section: Int) -> UIEdgeInsets) -> Self {
return update { $0.insetForSectionAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegateFlowLayout's collectionView(_:layout:minimumLineSpacingForSectionAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func minimumLineSpacingForSectionAt(handler: @escaping (_ section: Int) -> CGFloat) -> Self {
return update { $0.minimumLineSpacingForSectionAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegateFlowLayout's collectionView(_:layout:minimumInteritemSpacingForSectionAt:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func minimumInteritemSpacingForSectionAt(handler: @escaping (_ section: Int) -> CGFloat) -> Self {
return update { $0.minimumInteritemSpacingForSectionAt = handler }
}
/**
Equivalent to implementing UICollectionViewDelegateFlowLayout's collectionView(_:layout:referenceSizeForHeaderInSection:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func referenceSizeForHeaderInSection(handler: @escaping (_ section: Int) -> CGSize) -> Self {
return update { $0.referenceSizeForHeaderInSection = handler }
}
/**
Equivalent to implementing UICollectionViewDelegateFlowLayout's collectionView(_:layout:referenceSizeForFooterInSection:) method
* parameter handler: The closure that will be called in place of its equivalent delegate method
* returns: itself so you can daisy chain the other delegate calls
*/
@discardableResult
public func referenceSizeForFooterInSection(handler: @escaping (_ section: Int) -> CGSize) -> Self {
return update { $0.referenceSizeForFooterInSection = handler }
}
}
@available(iOS 9.0, *)
extension UICollectionView {
@discardableResult
@objc override func update(handler: (_ delegate: CollectionViewDelegate) -> Void) -> Self {
DelegateWrapper.update(self,
delegate: CollectionViewDelegate(),
delegates: &CollectionViewDelegate.delegates,
bind: UICollectionView.bind) {
handler($0.delegate)
}
return self
}
// MARK: Reset
/**
Clears any delegate/dataSource closures that were assigned to this
`UICollectionView`. This cleans up memory as well as sets the
delegate/dataSource properties to nil. This is typically only used for explicit
cleanup. You are not required to call this method.
*/
@objc override public func clearClosureDelegates() {
DelegateWrapper.remove(delegator: self, from: &CollectionViewDelegate.delegates)
UICollectionView.bind(self, nil)
}
fileprivate static func bind(_ delegator: UICollectionView, _ delegate: CollectionViewDelegate?) {
delegator.delegate = nil
delegator.dataSource = nil
delegator.delegate = delegate
delegator.dataSource = delegate
}
}
|
mit
|
61d946b7177433688f3244e56e5aaa2a
| 52.799242 | 206 | 0.717149 | 5.961802 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Views/Common/Data Rows/Base/Text Data Row/TextDataRow.swift
|
1
|
3451
|
//
// TextDataRow.swift
// MEGameTracker
//
// Created by Emily Ivie on 5/26/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
@IBDesignable
final public class TextDataRow: HairlineBorderView, IBViewable {
// MARK: Inspectable
@IBInspectable public var typeName: String = "None" {
didSet { setDummyDataRowType() }
}
@IBInspectable public var noPadding: Bool = false {
didSet {
setPadding(top: 0, right: 0, bottom: 0, left: 0)
}
}
@IBInspectable public var isHideOnEmpty: Bool = true
// MARK: Outlets
@IBOutlet public weak var textView: MarkupTextView?
@IBOutlet public weak var leadingPaddingConstraint: NSLayoutConstraint?
@IBOutlet public weak var trailingPaddingConstraint: NSLayoutConstraint?
@IBOutlet public weak var bottomPaddingConstraint: NSLayoutConstraint?
@IBOutlet public weak var topPaddingConstraint: NSLayoutConstraint?
@IBOutlet public weak var rowDivider: HairlineBorderView?
// MARK: Properties
private weak var heightConstraint: NSLayoutConstraint?
public var didSetup = false
public var isSettingUp = false
var isChangingTableHeader = false
// Protocol: IBViewable
public var isAttachedNibWrapper = false
public var isAttachedNib = false
// MARK: IBViewable
override public func awakeFromNib() {
super.awakeFromNib()
_ = attachOrAttachedNib()
}
override public func prepareForInterfaceBuilder() {
_ = attachOrAttachedNib()
super.prepareForInterfaceBuilder()
}
// MARK: Hide when not initialized (as though if empty)
public override func layoutSubviews() {
if !UIWindow.isInterfaceBuilder && !isAttachedNib && isHideOnEmpty && !didSetup {
isHidden = true
} else {
setDummyDataRowType()
}
super.layoutSubviews()
}
public func setPadding(top: CGFloat, right: CGFloat, bottom: CGFloat, left: CGFloat) {
topPaddingConstraint?.constant = top
bottomPaddingConstraint?.constant = bottom
leadingPaddingConstraint?.constant = left
trailingPaddingConstraint?.constant = right
layoutIfNeeded()
}
/// reload table headers because they are finnicky.
/// to utilize, wrap the text header in a useless extra wrapper view, so we can pop it out and into a new wrapper.
func setupTableHeader() {
guard isAttachedNib else { attachOrAttachedNib()?.setupTableHeader(); return }
guard !isChangingTableHeader,
let wrapperNib = self.superview,
let superview = wrapperNib.superview,
let tableView = superview.superview as? UITableView,
tableView.tableHeaderView == superview
else { return }
isChangingTableHeader = true
wrapperNib.removeFromSuperview()
wrapperNib.frame.size.height = wrapperNib.bounds.height
let newWrapper = UIView(frame: bounds)
newWrapper.addSubview(wrapperNib)
wrapperNib.fillView(newWrapper)
tableView.tableHeaderView = newWrapper
tableView.reloadData()
isChangingTableHeader = false
}
// MARK: Customization Options
func setDummyDataRowType() {
guard (isInterfaceBuilder || App.isInitializing) && !didSetup && isAttachedNibWrapper else { return }
var dataRowType: TextDataRowType?
switch typeName {
case "Aliases": dataRowType = AliasesType()
case "Availability": dataRowType = AvailabilityRowType()
case "Unavailability": dataRowType = UnavailabilityRowType()
case "Description": dataRowType = DescriptionType()
case "OriginHint": dataRowType = OriginHintType()
default: break
}
dataRowType?.row = self
dataRowType?.setupView()
}
}
|
mit
|
fed694c84c6a42579eec3bf2cc8fe1f1
| 27.278689 | 115 | 0.752754 | 4.166667 | false | false | false | false |
catalanjrj/TIY-Assignments
|
Counter/Counter/ViewController.swift
|
1
|
4410
|
//
// ViewController.swift
// Swift-Counter
//
// Created by Ben Gohlke on 8/17/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
// The following variables and constants are called properties; they hold values that can be accessed from any method in this class
// This allows the app to set its current count when the app first loads.
// The line below simply generates a random number and then makes sure it falls within the bounds 1-100.
var currentCount: Int = Int(arc4random() % 100)
// These are called IBOutlets and are a kind of property; they connect elements in the storyboard with the code so you can update the UI elements from code.
@IBOutlet weak var countTextField: UITextField!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var stepper: UIStepper!
override func viewDidLoad()
{
super.viewDidLoad()
//
// 1. Once the currentCount variable is set, each of the UI elements on the screen need to be updated to match the currentCount.
// There is a method below that performs these steps. All you need to do perform a method call in the line below.
//
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateViewsWithCurrentCount()
{
// Here we are updating the different subviews in our main view with the current count.
//
// 2. The textfield needs to always show the current count. Fill in the blank below to set the text value of the textfield.
countTextField.text = "\(currentCount)"
//
// 3. Here we are setting the value property of the UISlider in the view. This causes the slider to set its handle to the
// appropriate position. Fill in the blank below.
slider.value = Float (currentCount)
//
// 4. We also need to update the value of the UIStepper. The user will not see any change to the stepper, but it needs to have a
// current value nonetheless, so when + or - is tapped, it will know what value to increment. Fill in the blanks below.
//
stepper.value = Double (currentCount)
}
// MARK: - Gesture recognizers
@IBAction func viewTapped(sender: UITapGestureRecognizer)
{
// This method is run whenever the user taps on the blank, white view (meaning they haven't tapped any of the controls on the
// view). It hides the keyboard if the user has edited the count textfield, and also updates the currentCount variable.
if countTextField.isFirstResponder()
{
countTextField.resignFirstResponder()
//
// 8. Hopefully you're seeing a pattern here. After we update the currentCount variable, what do we need to do next? Fill in
// the blank below.
//
currentCount = Int(countTextField.text!)!
updateViewsWithCurrentCount() }
}
// MARK: - Action handlers
@IBAction func sliderValueChanged(sender: UISlider)
{
//
// 5. This method will run whenever the value of the slider is changed by the user. The "sender" object passed in as an argument
// to this method represents the slider from the view. We need to take the value of the slider and use it to update the
// value of our "currentCount" instance variable. Fill in the blank below.
//
currentCount = Int(sender.value)
//
// 6. Once we update the value of currentCount, we need to make sure all the UI elements on the screen are updated to keep
// everything in sync. We have previously done this (look in viewDidLoad). Fill in the blank below.
//
updateViewsWithCurrentCount() }
@IBAction func stepperValueChanged(sender: UIStepper)
{
//
// 7. This method is run when the value of the stepper is changed by the user. If you've done steps 5 and 6 already, these steps
// should look pretty familiar, hint, hint. ;) Fill in the blanks below.
//
currentCount = Int(sender.value)
updateViewsWithCurrentCount() }
}
|
cc0-1.0
|
93cf4722f2585a45329bed6efc08f6c8
| 40.224299 | 160 | 0.646259 | 4.93841 | false | false | false | false |
mperovic/my41
|
MODList.swift
|
1
|
1432
|
//
// MODList.swift
// my41
//
// Created by Miroslav Perovic on 3.2.21..
// Copyright © 2021 iPera. All rights reserved.
//
import SwiftUI
struct MODList: View {
@ObservedObject var settingsState: SettingsState
private let mods: [MOD] = Array(MODs.getModFiles().values)
@Binding var showList: Bool
@State private var selectedModule: MOD?
var port: HPPort
var body: some View {
VStack {
HStack {
Button(action: {
showList = false
}, label: {
Text("Cancel")
})
.padding([.top, .leading], 10)
Spacer()
Button(action: {
switch port {
case .port1:
settingsState.module1 = selectedModule
case .port2:
settingsState.module2 = selectedModule
case .port3:
settingsState.module3 = selectedModule
case .port4:
settingsState.module4 = selectedModule
}
showList = false
}, label: {
Text("Apply")
})
.padding([.top, .trailing], 10)
}
List {
ForEach(mods, id: \.self) { mod in
MODDetailsView(module: mod, short: false)
.onTapGesture {
selectedModule = mod
}
.listRowBackground(selectedModule == mod ? Color(UIColor.lightGray) : Color.clear)
}
}
}
}
}
struct MODList_Previews: PreviewProvider {
@State static var showList = true
static var previews: some View {
MODList(settingsState: SettingsState(), showList: $showList, port: .port3)
}
}
|
bsd-3-clause
|
1bfad62543621250a88ab43e0372e5a6
| 20.044118 | 88 | 0.625437 | 3.390995 | false | false | false | false |
ITzTravelInTime/TINU
|
TINU/Diskutil/DiskutilInfo.swift
|
1
|
2158
|
/*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Foundation
import Command
import TINUSerialization
public extension Diskutil{
final class Info{
private static var _id: BSDID! = nil
private static var _out: String! = nil
class func getPlist( for path: Path ) -> String?{
return Diskutil.performCommand(withArgs: ["info", "-plist", path])?.outputString()
}
class func getProperty(for id: BSDID, named: String) -> Any?{
//do{
/*
if id.rawValue.isEmpty{
return nil
}
*/
//probably another check is needed to avoid having different devices plugged one after the other and all having the same id being used with the info from one
if _id != id || _out == nil{
_id = id
//_out = Command.getOut(cmd: "diskutil info -plist \"" + id + "\"") ?? ""
guard let out = getPlist(for: id.rawValue) else { return nil }
_out = out
if _out.isEmpty{
_out = nil
return nil
}
}
if let dict = [String: Any].init(fromPlistSerialisedString: _out) {
return dict[named]
}
/*
if let dict = try Decode.plistToDictionary(from: _out) as? [String: Any]{
return dict[named]
}
}catch let err{
print("Getting diskutil info property decoding error: \(err.localizedDescription)")
}
*/
return nil
}
class func resetCache(){
_out = nil
_id = nil
}
}
}
typealias dm = Diskutil.Info
|
gpl-2.0
|
92acc86d857dc45d49056e3cf1cfdb6d
| 24.388235 | 160 | 0.68582 | 3.682594 | false | false | false | false |
benkraus/Operations
|
Operations/Operation.swift
|
1
|
14458
|
/*
The MIT License (MIT)
Original work Copyright (c) 2015 pluralsight
Modified work Copyright 2016 Ben Kraus
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 Foundation
/**
The subclass of `NSOperation` from which all other operations should be derived.
This class adds both Conditions and Observers, which allow the operation to define
extended readiness requirements, as well as notify many interested parties
about interesting operation state changes
*/
public class Operation: NSOperation {
/* The completionBlock property has unexpected behaviors such as executing twice and executing on unexpected threads. BlockObserver
* executes in an expected manner.
*/
@available(*, deprecated, message="use BlockObserver completions instead")
override public var completionBlock: (() -> Void)? {
set {
fatalError("The completionBlock property on NSOperation has unexpected behavior and is not supported in PSOperations.Operation 😈")
}
get {
return nil
}
}
// use the KVO mechanism to indicate that changes to "state" affect other properties as well
class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> {
return ["state", "cancelledState"]
}
class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> {
return ["cancelledState"]
}
// MARK: State Management
private enum State: Int, Comparable {
/// The initial state of an `Operation`.
case Initialized
/// The `Operation` is ready to begin evaluating conditions.
case Pending
/// The `Operation` is evaluating conditions.
case EvaluatingConditions
/**
The `Operation`'s conditions have all been satisfied, and it is ready
to execute.
*/
case Ready
/// The `Operation` is executing.
case Executing
/**
Execution of the `Operation` has finished, but it has not yet notified
the queue of this.
*/
case Finishing
/// The `Operation` has finished executing.
case Finished
func canTransitionToState(target: State, operationIsCancelled cancelled: Bool) -> Bool {
switch (self, target) {
case (.Initialized, .Pending):
return true
case (.Pending, .EvaluatingConditions):
return true
case (.Pending, .Finishing) where cancelled:
return true
case (.Pending, .Ready) where cancelled:
return true
case (.EvaluatingConditions, .Ready):
return true
case (.Ready, .Executing):
return true
case (.Ready, .Finishing):
return true
case (.Executing, .Finishing):
return true
case (.Finishing, .Finished):
return true
default:
return false
}
}
}
/**
Indicates that the Operation can now begin to evaluate readiness conditions,
if appropriate.
*/
func didEnqueue() {
state = .Pending
}
/// Private storage for the `state` property that will be KVO observed.
private var _state = State.Initialized
/// A lock to guard reads and writes to the `_state` property
private let stateLock = NSLock()
private var state: State {
get {
return stateLock.withCriticalScope {
_state
}
}
set(newState) {
/*
It's important to note that the KVO notifications are NOT called from inside
the lock. If they were, the app would deadlock, because in the middle of
calling the `didChangeValueForKey()` method, the observers try to access
properties like "isReady" or "isFinished". Since those methods also
acquire the lock, then we'd be stuck waiting on our own lock. It's the
classic definition of deadlock.
*/
willChangeValueForKey("state")
stateLock.withCriticalScope { Void -> Void in
guard _state != .Finished else {
return
}
assert(_state.canTransitionToState(newState, operationIsCancelled: cancelled), "Performing invalid state transition.")
_state = newState
}
didChangeValueForKey("state")
}
}
private let readyLock = NSRecursiveLock()
// Here is where we extend our definition of "readiness".
override public var ready: Bool {
var _ready = false
readyLock.withCriticalScope {
switch state {
case .Initialized:
// If the operation has been cancelled, "isReady" should return true
_ready = cancelled
case .Pending:
// If the operation has been cancelled, "isReady" should return true
guard !cancelled else {
state = .Ready
_ready = true
return
}
// If super isReady, conditions can be evaluated
if super.ready {
evaluateConditions()
}
// Until conditions have been evaluated, "isReady" returns false
_ready = false
case .Ready:
_ready = super.ready || cancelled
default:
_ready = false
}
}
return _ready
}
public var userInitiated: Bool {
get {
return qualityOfService == .UserInitiated
}
set {
assert(state < .Executing, "Cannot modify userInitiated after execution has begun.")
qualityOfService = newValue ? .UserInitiated : .Default
}
}
override public var executing: Bool {
return state == .Executing
}
override public var finished: Bool {
return state == .Finished
}
var _cancelled = false {
willSet {
willChangeValueForKey("cancelledState")
}
didSet {
didChangeValueForKey("cancelledState")
if _cancelled != oldValue && _cancelled == true {
for observer in observers {
observer.operationDidCancel(self)
}
}
}
}
override public var cancelled: Bool {
return _cancelled
}
private func evaluateConditions() {
assert(state == .Pending && !cancelled, "evaluateConditions() was called out-of-order")
state = .EvaluatingConditions
guard conditions.count > 0 else {
state = .Ready
return
}
OperationConditionEvaluator.evaluate(conditions, operation: self) { failures in
if !failures.isEmpty {
self.cancelWithErrors(failures)
}
//We must preceed to have the operation exit the queue
self.state = .Ready
}
}
// MARK: Observers and Conditions
private(set) var conditions = [OperationCondition]()
public func addCondition(condition: OperationCondition) {
assert(state < .EvaluatingConditions, "Cannot modify conditions after execution has begun.")
conditions.append(condition)
}
private(set) var observers = [OperationObserver]()
public func addObserver(observer: OperationObserver) {
assert(state < .Executing, "Cannot modify observers after execution has begun.")
observers.append(observer)
}
override public func addDependency(operation: NSOperation) {
assert(state <= .Executing, "Dependencies cannot be modified after execution has begun.")
super.addDependency(operation)
}
// MARK: Execution and Cancellation
override final public func start() {
// NSOperation.start() contains important logic that shouldn't be bypassed.
super.start()
// If the operation has been cancelled, we still need to enter the "Finished" state.
if cancelled {
finish()
}
}
override final public func main() {
assert(state == .Ready, "This operation must be performed on an operation queue.")
if _internalErrors.isEmpty && !cancelled {
state = .Executing
for observer in observers {
observer.operationDidStart(self)
}
execute()
}
else {
finish()
}
}
/**
`execute()` is the entry point of execution for all `Operation` subclasses.
If you subclass `Operation` and wish to customize its execution, you would
do so by overriding the `execute()` method.
At some point, your `Operation` subclass must call one of the "finish"
methods defined below; this is how you indicate that your operation has
finished its execution, and that operations dependent on yours can re-evaluate
their readiness state.
*/
public func execute() {
print("\(self.dynamicType) must override `execute()`.")
finish()
}
private var _internalErrors = [NSError]()
override public func cancel() {
if finished {
return
}
_cancelled = true
if state > .Ready {
finish()
}
}
public func cancelWithErrors(errors: [NSError]) {
_internalErrors += errors
cancel()
}
public func cancelWithError(error: NSError) {
cancelWithErrors([error])
}
public final func produceOperation(operation: NSOperation) {
for observer in observers {
observer.operation(self, didProduceOperation: operation)
}
}
// MARK: Finishing
/**
Most operations may finish with a single error, if they have one at all.
This is a convenience method to simplify calling the actual `finish()`
method. This is also useful if you wish to finish with an error provided
by the system frameworks. As an example, see `DownloadEarthquakesOperation`
for how an error from an `NSURLSession` is passed along via the
`finishWithError()` method.
*/
public final func finishWithError(error: NSError?) {
if let error = error {
finish([error])
}
else {
finish()
}
}
/**
A private property to ensure we only notify the observers once that the
operation has finished.
*/
private var hasFinishedAlready = false
public final func finish(errors: [NSError] = []) {
if !hasFinishedAlready {
hasFinishedAlready = true
state = .Finishing
let combinedErrors = _internalErrors + errors
finished(combinedErrors)
for observer in observers {
observer.operationDidFinish(self, errors: combinedErrors)
}
state = .Finished
}
}
/**
Subclasses may override `finished(_:)` if they wish to react to the operation
finishing with errors. For example, the `LoadModelOperation` implements
this method to potentially inform the user about an error when trying to
bring up the Core Data stack.
*/
public func finished(errors: [NSError]) {
// No op.
}
override public func waitUntilFinished() {
/*
Waiting on operations is almost NEVER the right thing to do. It is
usually superior to use proper locking constructs, such as `dispatch_semaphore_t`
or `dispatch_group_notify`, or even `NSLocking` objects. Many developers
use waiting when they should instead be chaining discrete operations
together using dependencies.
To reinforce this idea, invoking `waitUntilFinished()` will crash your
app, as incentive for you to find a more appropriate way to express
the behavior you're wishing to create.
*/
fatalError("Waiting on operations is an anti-pattern. Remove this ONLY if you're absolutely sure there is No Other Way™.")
}
}
// Simple operator functions to simplify the assertions used above.
private func <(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
private func ==(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue == rhs.rawValue
}
|
mit
|
6eda8ce63aea2a68cca5a5a807ddfa54
| 31.625282 | 142 | 0.583893 | 5.643499 | false | false | false | false |
BirdBrainTechnologies/Hummingbird-iOS-Support
|
BirdBlox/BirdBlox/BBTBackendServer.swift
|
1
|
8092
|
//
// BBTBackendServer.swift
// BirdBlox
//
// Created by Jeremy Huang on 2017-05-30.
// Copyright © 2017年 Birdbrain Technologies LLC. All rights reserved.
//
import Foundation
//import Swifter
import WebKit
class BBTBackendServer: NSObject, WKScriptMessageHandler {
var pathDict: Dictionary<String, ((HttpRequest) -> HttpResponse)>
let backgroundQueue = DispatchQueue(label: "background", qos: .background,
attributes: .concurrent)
let regularQueue = DispatchQueue(label: "birdblox", qos: .userInitiated,
attributes: .concurrent)
// let regularQueue = DispatchQueue.global(qos: .userInteractive)
// let backgroundQueue = DispatchQueue.global(qos: .background)
let router = HttpRouter()
private var clearingRegularQueue = false
let queueClearingLock = NSCondition()
let backgroundQueueBlockCountLock = NSCondition()
var backgroundQueueBlockCount = 0
let maxBackgroundQueueBlockCount = 30
override init() {
pathDict = Dictionary()
}
private func notFoundHandler(request: HttpRequest) -> HttpResponse {
if request.address == nil || request.address != BBTLocalHostIP {
#if DEBUG
#else
return .forbidden
#endif
}
if let handler = pathDict[request.path] {
return handler(request)
}
let address = request.address ?? "unknown"
NSLog("Unable to find handler for Request \(request.path) from address \(address).")
return .notFound
}
subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
set(handler) {
if let handler = handler {
func guardedHandler(request: HttpRequest) -> HttpResponse {
NSLog("Faux HTTP Request \(request.path) from address \(request.address ?? "unknown").")
if request.address == nil || request.address != BBTLocalHostIP{
#if DEBUG
NSLog("Permitting external request in DEBUG mode.")
#else
NSLog("Forbidding external request.")
return .forbidden
#endif
}
//Only use the guarded handler if there is a handler to guard
return handler(request)
}
self.pathDict[path] = guardedHandler
self.router.register(nil, path: path, handler: guardedHandler)
} else {
self.pathDict.removeValue(forKey: path)
self.router.register(nil, path: path, handler: nil)
}
}
get{ return pathDict[path] }
}
public func handleNativeCall(responseID: String, requestStr: String, body: String?,
background: String = "true") {
let nativeCallBlock = {
let request = HttpRequest()
request.address = BBTLocalHostIP
request.path = requestStr
request.queryParams = self.extractQueryParams(request.path)
if let bodyBytes = body?.utf8 {
request.body = [UInt8](bodyBytes)
}
let (params, handler) =
self.router.route(nil, path: request.path) ?? ([:], self.notFoundHandler)
request.params = params
let resp = handler(request)
let code = resp.statusCode()
var bodyStr = ""
//Extract the body and put it in bodyStr if possible
let len = resp.content().length
if len > 0 {
let bytesAccessor = BytesAccessor(length: len)
let bodyClosure = resp.content().write ?? { try $0.write([]) }
do {
try bodyClosure(bytesAccessor)
if let s = String(data: bytesAccessor.data, encoding: .utf8) {
bodyStr = s
}
} catch {
NSLog("Unable to obtain response data.")
}
}
let _ = FrontendCallbackCenter.shared
.sendFauxHTTPResponse(id: responseID, status: code, obody: bodyStr)
}
if background == "false" {
self.regularQueue.async(execute: nativeCallBlock)
}
else if self.backgroundQueueBlockCount < self.maxBackgroundQueueBlockCount {
self.backgroundQueueBlockCountLock.lock()
self.backgroundQueueBlockCount += 1
self.backgroundQueueBlockCountLock.unlock()
let cancellableBlock = {
if !self.clearingRegularQueue {
nativeCallBlock()
}
self.backgroundQueueBlockCountLock.lock()
self.backgroundQueueBlockCount -= 1
self.backgroundQueueBlockCountLock.unlock()
}
self.backgroundQueue.async(execute: cancellableBlock)
} else {
NSLog("Dropped request because max background queue size exceeded. \(requestStr)")
}
}
//Only one instance of this function can be run at a time
//Swift does not have a native way to do a mutex lock yet.
//Not much point anymore because queue is unlikely to have backlog.
public func clearBackgroundQueue(completion: (() -> Void)? = nil) {
self.queueClearingLock.lock()
self.clearingRegularQueue = true
self.backgroundQueue.async {
self.clearingRegularQueue = false
}
self.queueClearingLock.unlock()
if let comp = completion {
comp()
}
}
//MARK: WKScriptMessageHandler
/*! @abstract Invoked when a script message is received from a webpage.
@param userContentController The user content controller invoking the
delegate method.
@param message The script message received.
*/
@available(iOS 8.0, *)
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
// NSLog("Sever get webkit message: \(message.name)")
// print(message.body)
guard message.name == "serverSubstitute",
let obj = message.body as? NSDictionary,
let requestStr = obj["request"] as? String,
let body = obj["body"] as? String,
let id = obj["id"] as? String,
let background = obj["inBackground"] as? String else {
print("Unable to respond")
return
}
NSLog("bg \(background) faux req \(requestStr)")
self.handleNativeCall(responseID: id, requestStr: requestStr, body: body,
background: background)
}
//TODO: Delete
func start() {
NSLog("faux Server faux started, state \(9)")
}
func stop() {
NSLog("faux Server faux stopping")
}
//MARK: For Native Call compatibility with HttpServer
//Used to extract Http response bodies
class BytesAccessor: HttpResponseBodyWriter {
var data: Data
let len: Int
init(length: Int) {
self.data = Data(capacity: length)
self.len = length
}
func write(_ data: [UInt8]) throws {
self.data.append(contentsOf: data)
}
func write(_ file: String.File) throws {
var bytes = Array<UInt8>(repeating: 0, count: self.len)
let _ = try file.read(&bytes)
try self.write(bytes)
}
func write(_ data: Data) throws {
// data.copyBytes(to: &self.bytes, count: bytes.count)
self.data = data
}
func write(_ data: NSData) throws {
try self.write(data as Data)
}
func write(_ data: ArraySlice<UInt8>) throws -> () {
let bytes = Array(data)
try self.write(bytes)
}
}
//Query parameter extraction function from Swifter
//Unfortunately we can't just call it because we need to make an HttpRequest from
//the native call and not just a socket. (This function is private.)
private func extractQueryParams(_ url: String) -> [(String, String)] {
guard let questionMark = url.index(of: "?") else {
return []
}
let queryStart = url.index(after: questionMark)
guard url.endIndex > queryStart else {
return []
}
let query = String(url[queryStart..<url.endIndex])
return query.components(separatedBy: "&")
.reduce([(String, String)]()) { (c, s) -> [(String, String)] in
guard let nameEndIndex = s.index(of: "="),
let name = String(s[s.startIndex..<nameEndIndex]).removingPercentEncoding else {
return c
}
let valueStartIndex = s.index(nameEndIndex, offsetBy: 1)
guard valueStartIndex < s.endIndex,
let value = String(s[valueStartIndex..<s.endIndex]).removingPercentEncoding else {
return c + [(name, "")]
}
return c + [(name, value)]
}
}
}
|
mit
|
ebc5cd21d798544b9edb948bc16d3d44
| 28.848708 | 108 | 0.644332 | 3.896435 | false | false | false | false |
barkinet/WordPress-iOS
|
WordPress/WordPressTodayWidget/TodayViewController.swift
|
1
|
4986
|
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet var siteNameLabel: UILabel!
@IBOutlet var visitorsCountLabel: UILabel!
@IBOutlet var visitorsLabel: UILabel!
@IBOutlet var viewsCountLabel: UILabel!
@IBOutlet var viewsLabel: UILabel!
var siteName: String = ""
var visitorCount: String = ""
var viewCount: String = ""
var siteId: NSNumber?
override func viewDidLoad() {
super.viewDidLoad()
let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)!
self.siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as! NSNumber?
visitorsLabel?.text = NSLocalizedString("Visitors", comment: "Stats Visitors Label")
viewsLabel?.text = NSLocalizedString("Views", comment: "Stats Views Label")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Manual state restoration
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(self.siteName, forKey: WPStatsTodayWidgetUserDefaultsSiteNameKey)
userDefaults.setObject(self.visitorCount, forKey: WPStatsTodayWidgetUserDefaultsVisitorCountKey)
userDefaults.setObject(self.viewCount, forKey: WPStatsTodayWidgetUserDefaultsViewCountKey)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Manual state restoration
let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)!
self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? ""
let userDefaults = NSUserDefaults.standardUserDefaults()
self.visitorCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsVisitorCountKey) ?? "0"
self.viewCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsViewCountKey) ?? "0"
self.siteNameLabel?.text = self.siteName
self.visitorsCountLabel?.text = self.visitorCount
self.viewsCountLabel?.text = self.viewCount
}
@IBAction func launchContainingApp() {
self.extensionContext!.openURL(NSURL(string: "\(WPCOM_SCHEME)://viewstats?siteId=\(siteId!)")!, completionHandler: nil)
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
// If an error is encoutered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)!
let siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as! NSNumber?
self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? ""
let timeZoneName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteTimeZoneKey)
let oauth2Token = self.getOAuth2Token()
if siteId == nil || timeZoneName == nil || oauth2Token == nil {
WPDDLogWrapper.logError("Missing site ID, timeZone or oauth2Token")
let bundle = NSBundle(forClass: TodayViewController.classForCoder())
NCWidgetController.widgetController().setHasContent(false, forWidgetWithBundleIdentifier: bundle.bundleIdentifier)
completionHandler(NCUpdateResult.Failed)
return
}
let timeZone = NSTimeZone(name: timeZoneName!)
var statsService: WPStatsService = WPStatsService(siteId: siteId, siteTimeZone: timeZone, oauth2Token: oauth2Token, andCacheExpirationInterval:0)
statsService.retrieveTodayStatsWithCompletionHandler({ (wpStatsSummary: StatsSummary!) -> Void in
WPDDLogWrapper.logInfo("Downloaded data in the Today widget")
self.visitorCount = wpStatsSummary.visitors
self.viewCount = wpStatsSummary.views
self.siteNameLabel?.text = self.siteName
self.visitorsCountLabel?.text = self.visitorCount
self.viewsCountLabel?.text = self.viewCount
completionHandler(NCUpdateResult.NewData)
}, failureHandler: { (error) -> Void in
WPDDLogWrapper.logError("\(error)")
completionHandler(NCUpdateResult.Failed)
})
}
func getOAuth2Token() -> String? {
var error:NSError?
var oauth2Token:NSString? = SFHFKeychainUtils.getPasswordForUsername(WPStatsTodayWidgetOAuth2TokenKeychainUsername, andServiceName: WPStatsTodayWidgetOAuth2TokenKeychainServiceName, accessGroup: WPStatsTodayWidgetOAuth2TokenKeychainAccessGroup, error: &error)
return oauth2Token as String?
}
}
|
gpl-2.0
|
83c67ef4011b5b114733ebd932e25284
| 45.607477 | 267 | 0.697954 | 5.665909 | false | false | false | false |
carabina/string-in-chain
|
Pod/Classes/StringInChain.swift
|
1
|
1224
|
//
// StringInChain.swift
// StringInChain
//
// Created by Lukasz Solniczek on 22.06.2015.
// Copyright (c) 2015 Lukasz Solniczek. All rights reserved.
//
import Foundation
public class StringInChain {
var stringToMatch: String?
var baseText: NSString
public var attrString: NSMutableAttributedString
init(string: String) {
self.baseText = string
self.attrString = NSMutableAttributedString(string: string)
}
init(string: String, stringToMatch: String) {
self.baseText = string
self.stringToMatch = stringToMatch
self.attrString = NSMutableAttributedString(string: string)
}
public func match(text: String) -> StringInChain {
stringToMatch = text
return self
}
public func match(from begin: Int, to: Int) -> StringInChain {
let range = NSMakeRange(begin, (to-begin)+1)
stringToMatch = baseText.substringWithRange(range)
return self
}
func setRange() -> NSRange {
if let stringToMatch = stringToMatch as String? {
return baseText.rangeOfString(stringToMatch)
}
return baseText.rangeOfString(baseText as String)
}
}
|
mit
|
c924287469b9014726226d4b2fdf5126
| 25.608696 | 67 | 0.647059 | 4.402878 | false | false | false | false |
Geor9eLau/WorkHelper
|
Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartGroupedBarsLayer.swift
|
1
|
4876
|
//
// ChartGroupedBarsLayer.swift
// Examples
//
// Created by ischuetz on 19/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public final class ChartPointsBarGroup<T: ChartBarModel> {
let constant: ChartAxisValue
let bars: [T]
public init(constant: ChartAxisValue, bars: [T]) {
self.constant = constant
self.bars = bars
}
}
open class ChartGroupedBarsLayer<T: ChartBarModel>: ChartCoordsSpaceLayer {
fileprivate let groups: [ChartPointsBarGroup<T>]
fileprivate let barSpacing: CGFloat?
fileprivate let groupSpacing: CGFloat?
fileprivate let horizontal: Bool
fileprivate let animDuration: Float
init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, groups: [ChartPointsBarGroup<T>], horizontal: Bool = false, barSpacing: CGFloat?, groupSpacing: CGFloat?, animDuration: Float) {
self.groups = groups
self.horizontal = horizontal
self.barSpacing = barSpacing
self.groupSpacing = groupSpacing
self.animDuration = animDuration
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
func barsGenerator(barWidth: CGFloat) -> ChartBarsViewGenerator<T> {
fatalError("override")
}
override open func chartInitialized(chart: Chart) {
let axis = self.horizontal ? self.yAxis : self.xAxis
let groupAvailableLength = (axis.length - (self.groupSpacing ?? 0) * CGFloat(self.groups.count)) / CGFloat(groups.count + 1)
let maxBarCountInGroup = self.groups.reduce(CGFloat(0)) {maxCount, group in
max(maxCount, CGFloat(group.bars.count))
}
let barWidth = ((groupAvailableLength - ((self.barSpacing ?? 0) * (maxBarCountInGroup - 1))) / CGFloat(maxBarCountInGroup))
let barsGenerator = self.barsGenerator(barWidth: barWidth)
let calculateConstantScreenLoc: (_ axis: ChartAxisLayer, _ index: Int, _ group: ChartPointsBarGroup<T>) -> CGFloat = {axis, index, group in
let totalWidth = CGFloat(group.bars.count) * barWidth + ((self.barSpacing ?? 0) * (maxBarCountInGroup - 1))
let groupCenter = axis.screenLocForScalar(group.constant.scalar)
let origin = groupCenter - totalWidth / 2
return origin + CGFloat(index) * (barWidth + (self.barSpacing ?? 0)) + barWidth / 2
}
for group in self.groups {
for (index, bar) in group.bars.enumerated() {
let constantScreenLoc: CGFloat = {
if barsGenerator.direction == .leftToRight {
return calculateConstantScreenLoc(self.yAxis, index, group)
} else {
return calculateConstantScreenLoc(self.xAxis, index, group)
}
}()
chart.addSubview(barsGenerator.generateView(bar, constantScreenLoc: constantScreenLoc, bgColor: bar.bgColor, animDuration: self.animDuration))
}
}
}
}
public typealias ChartGroupedPlainBarsLayer = ChartGroupedPlainBarsLayer_<Any>
open class ChartGroupedPlainBarsLayer_<N>: ChartGroupedBarsLayer<ChartBarModel> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, groups: [ChartPointsBarGroup<ChartBarModel>], horizontal: Bool, barSpacing: CGFloat?, groupSpacing: CGFloat?, animDuration: Float) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, groups: groups, horizontal: horizontal, barSpacing: barSpacing, groupSpacing: groupSpacing, animDuration: animDuration)
}
override func barsGenerator(barWidth: CGFloat) -> ChartBarsViewGenerator<ChartBarModel> {
return ChartBarsViewGenerator(horizontal: self.horizontal, xAxis: self.xAxis, yAxis: self.yAxis, chartInnerFrame: self.innerFrame, barWidth: barWidth, barSpacing: self.barSpacing)
}
}
public typealias ChartGroupedStackedBarsLayer = ChartGroupedStackedBarsLayer_<Any>
open class ChartGroupedStackedBarsLayer_<N>: ChartGroupedBarsLayer<ChartStackedBarModel> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, groups: [ChartPointsBarGroup<ChartStackedBarModel>], horizontal: Bool, barSpacing: CGFloat?, groupSpacing: CGFloat?, animDuration: Float) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, groups: groups, horizontal: horizontal, barSpacing: barSpacing, groupSpacing: groupSpacing, animDuration: animDuration)
}
override func barsGenerator(barWidth: CGFloat) -> ChartBarsViewGenerator<ChartStackedBarModel> {
return ChartStackedBarsViewGenerator(horizontal: horizontal, xAxis: xAxis, yAxis: yAxis, chartInnerFrame: innerFrame, barWidth: barWidth, barSpacing: barSpacing)
}
}
|
mit
|
16ed067c3b8fe120a6efe089b44b1498
| 44.570093 | 230 | 0.686833 | 4.827723 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Storage/Rust/RustRemoteTabs.swift
|
2
|
5613
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
import Shared
@_exported import MozillaAppServices
public class RustRemoteTabs {
let databasePath: String
let queue: DispatchQueue
var storage: TabsStorage?
private(set) var isOpen = false
private var didAttemptToMoveToBackup = false
public init(databasePath: String) {
self.databasePath = databasePath
queue = DispatchQueue(label: "RustRemoteTabs queue: \(databasePath)", attributes: [])
}
private func open() -> NSError? {
storage = TabsStorage(databasePath: databasePath)
isOpen = true
return nil
}
private func close() -> NSError? {
storage = nil
isOpen = false
return nil
}
public func reopenIfClosed() -> NSError? {
var error: NSError?
queue.sync {
guard !isOpen else { return }
error = open()
}
return error
}
public func forceClose() -> NSError? {
var error: NSError?
queue.sync {
guard isOpen else { return }
error = close()
}
return error
}
public func sync(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = TabsApiError.UnexpectedTabsError(reason: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try _ = self.storage?.sync(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let tabsError = err as? TabsApiError {
SentryIntegration.shared.sendWithStacktrace(
message: "Tabs error when syncing Tabs database",
tag: SentryTag.rustRemoteTabs,
severity: .error,
description: tabsError.localizedDescription)
} else {
SentryIntegration.shared.sendWithStacktrace(
message: "Unknown error when opening Rust Tabs database",
tag: SentryTag.rustRemoteTabs,
severity: .error,
description: err.localizedDescription)
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func resetSync() -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = TabsApiError.UnexpectedTabsError(reason: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage?.reset()
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func setLocalTabs(localTabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
let deferred = Deferred<Maybe<Int>>()
queue.async {
let tabs = localTabs.map { $0.toRemoteTabRecord() }
if let storage = self.storage {
storage.setLocalTabs(remoteTabs: tabs)
deferred.fill(Maybe(success: tabs.count))
} else {
let error = TabsApiError.UnexpectedTabsError(reason: "Unknown error when setting local Rust Tabs")
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
return deferred
}
public func getAll() -> Deferred<Maybe<[ClientRemoteTabs]>> {
// Note: this call will get all of the client and tabs data from
// the application storage tabs store without filter against the
// BrowserDB client records.
let deferred = Deferred<Maybe<[ClientRemoteTabs]>>()
queue.async {
guard self.isOpen else {
let error = TabsApiError.UnexpectedTabsError(reason: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
if let storage = self.storage {
let records = storage.getAll()
deferred.fill(Maybe(success: records))
} else {
deferred.fill(Maybe(failure: TabsApiError.UnexpectedTabsError(reason: "Unknown error when getting all Rust Tabs") as MaybeErrorType))
}
}
return deferred
}
}
public extension RemoteTabRecord {
func toRemoteTab(client: RemoteClient) -> RemoteTab? {
guard let url = Foundation.URL(string: self.urlHistory[0]) else { return nil }
let history = self.urlHistory[1...].map { url in Foundation.URL(string: url) }.compactMap { $0 }
let icon = self.icon != nil ? Foundation.URL(fileURLWithPath: self.icon ?? "") : nil
return RemoteTab(clientGUID: client.guid, URL: url, title: self.title, history: history, lastUsed: Timestamp(self.lastUsed), icon: icon)
}
}
public extension ClientRemoteTabs {
func toClientAndTabs(client: RemoteClient) -> ClientAndTabs {
return ClientAndTabs(client: client, tabs: self.remoteTabs.map { $0.toRemoteTab(client: client)}.compactMap { $0 })
}
}
|
mpl-2.0
|
06a33f27916ae014d8d92500bab564a3
| 31.074286 | 149 | 0.573668 | 5.020572 | false | false | false | false |
glessard/swift
|
test/Interpreter/Inputs/type_wrapper_defs.swift
|
1
|
3106
|
@typeWrapper
public struct Wrapper<S> {
var underlying: S
public init(memberwise: S) {
print("Wrapper.init(\(memberwise))")
self.underlying = memberwise
}
public subscript<V>(storageKeyPath path: WritableKeyPath<S, V>) -> V {
get {
print("in getter")
return underlying[keyPath: path]
}
set {
print("in setter => \(newValue)")
underlying[keyPath: path] = newValue
}
}
}
@propertyWrapper
public struct PropWrapper<Value> {
public var value: Value
public init(wrappedValue: Value) {
self.value = wrappedValue
}
public var projectedValue: Self { return self }
public var wrappedValue: Value {
get {
self.value
}
set {
self.value = newValue
}
}
}
@propertyWrapper
public struct PropWrapperWithoutInit<Value> {
public var value: Value
public init(value: Value) {
self.value = value
}
public var projectedValue: Self { return self }
public var wrappedValue: Value {
get {
self.value
}
set {
self.value = newValue
}
}
}
@propertyWrapper
public struct PropWrapperWithoutProjection<Value> {
public var value: Value
public init(wrappedValue: Value) {
self.value = wrappedValue
}
public var wrappedValue: Value {
get {
self.value
}
set {
self.value = newValue
}
}
}
@Wrapper
public class Person<T> {
public var name: String
public var projects: [T]
}
@Wrapper
public struct PersonWithDefaults {
public var name: String = "<no name>"
public var age: Int = 99
}
@Wrapper
public struct PropWrapperTest {
@PropWrapper public var test: Int
}
@Wrapper
public struct DefaultedPropWrapperTest {
@PropWrapper public var test: Int = 0
}
@Wrapper
public struct DefaultedPropWrapperWithArgTest {
@PropWrapper(wrappedValue: 3) public var test: Int
}
@Wrapper
public struct PropWrapperNoInitTest {
@PropWrapperWithoutInit public var a: Int
@PropWrapperWithoutInit(value: "b") public var b: String
}
@Wrapper
public struct PropWrapperNoProjectionTest {
@PropWrapperWithoutProjection public var a: Int = 0
@PropWrapperWithoutProjection(wrappedValue: PropWrapper(wrappedValue: "b")) @PropWrapper public var b: String
}
@Wrapper
public struct ComplexPropWrapperTest {
@PropWrapper public var a: [String] = ["a"]
@PropWrapperWithoutInit(value: PropWrapper(wrappedValue: [1, 2, 3])) @PropWrapper public var b: [Int]
}
@Wrapper
public struct PersonWithUnmanagedTest {
public let name: String
public lazy var age: Int = {
30
}()
public var placeOfBirth: String {
get { "Earth" }
}
@PropWrapper public var favoredColor: String = "red"
}
@Wrapper
public class ClassWithDesignatedInit {
public var a: Int
@PropWrapperWithoutInit public var b: [Int]
public init(a: Int, b: [Int] = [1, 2, 3]) {
$_storage = .init(memberwise: $Storage(a: 42, _b: PropWrapperWithoutInit(value: b)))
}
}
@Wrapper
public class PersonWithIgnoredAge {
public var name: String
@typeWrapperIgnored public var age: Int = 0
@typeWrapperIgnored @PropWrapper public var manufacturer: String?
}
|
apache-2.0
|
fe154eb7d94d2864ee83582569170c05
| 19.03871 | 111 | 0.688345 | 3.992288 | false | true | false | false |
CharlinFeng/Reflect
|
Reflect/Reflect/Dict2Model/Reflect+Parse.swift
|
1
|
8256
|
//
// Reflect+Parse.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
extension Reflect{
class func parsePlist(name: String) -> Self?{
let path = Bundle.main.path(forResource: name+".plist", ofType: nil)
if path == nil {return nil}
let dict = NSDictionary(contentsOfFile: path!)
if dict == nil {return nil}
return parse(dict: dict!)
}
class func parses(arr arr: NSArray) -> [Reflect]{
var models: [Reflect] = []
for (_ , dict) in arr.enumerated(){
let model = self.parse(dict: dict as! NSDictionary)
models.append(model)
}
return models
}
class func parse(dict dict: NSDictionary) -> Self{
let model = self.init()
let mappingDict = model.mappingDict()
let ignoreProperties = model.ignorePropertiesForParse()
model.properties { (name, type, value) -> Void in
let dataDictHasKey = dict[name] != nil
let mappdictDictHasKey = mappingDict?[name] != nil
let needIgnore = ignoreProperties == nil ? false : (ignoreProperties!).contains(name)
if (dataDictHasKey || mappdictDictHasKey) && !needIgnore {
let key = mappdictDictHasKey ? mappingDict![name]! : name
if !type.isArray {
if !type.isReflect {
if type.typeClass == Bool.self { //bool
model.setValue((dict[key] as AnyObject).boolValue, forKeyPath: name)
}else if type.isOptional && type.realType == ReflectType.RealType.String{
let v = dict[key]
if v != nil {
let str_temp = "\(v!)"
model.setValue(str_temp, forKeyPath: name)
}
}else{
model.setValue(dict[key], forKeyPath: name)
}
}else{
//这里是模型
//首选判断字典中是否有值
let dictValue = dict[key]
if dictValue != nil { //字典中有模型
let modelValue = model.value(forKeyPath: key)
if modelValue != nil { //子模型已经初始化
model.setValue((type.typeClass as! Reflect.Type).parse(dict: dict[key] as! NSDictionary), forKeyPath: name)
}else{ //子模型没有初始化
//先主动初始化
var tn = type.typeName ?? ""
var cls = ClassFromString(str: tn)
model.setValue((cls as! Reflect.Type).parse(dict: dict[key] as! NSDictionary), forKeyPath: name)
}
}
}
}else{
if let res = type.isAggregate(){
if res is Int.Type {
var arrAggregate: [Int] = []
arrAggregate = parseAggregateArray(arrDict: dict[key] as! NSArray, basicType: ReflectType.BasicType.Int, ins: 0)
model.setValue(arrAggregate, forKeyPath: name)
}else if res is Float.Type {
var arrAggregate: [Float] = []
arrAggregate = parseAggregateArray(arrDict: dict[key] as! NSArray, basicType: ReflectType.BasicType.Float, ins: 0.0)
model.setValue(arrAggregate, forKeyPath: name)
}else if res is Double.Type {
var arrAggregate: [Double] = []
arrAggregate = parseAggregateArray(arrDict: dict[key] as! NSArray, basicType: ReflectType.BasicType.Double, ins: 0.0)
model.setValue(arrAggregate, forKeyPath: name)
}else if res is String.Type {
var arrAggregate: [String] = []
arrAggregate = parseAggregateArray(arrDict: dict[key] as! NSArray, basicType: ReflectType.BasicType.String, ins: "")
model.setValue(arrAggregate, forKeyPath: name)
}else if res is NSNumber.Type {
var arrAggregate: [NSNumber] = []
arrAggregate = parseAggregateArray(arrDict: dict[key] as! NSArray, basicType: ReflectType.BasicType.NSNumber, ins: NSNumber())
model.setValue(arrAggregate, forKeyPath: name)
}else{
var arrAggregate: [AnyObject] = []
arrAggregate = dict[key] as! [AnyObject]
model.setValue(arrAggregate, forKeyPath: name)
}
}else{
let elementModelType = ReflectType.makeClass(type: type) as! Reflect.Type
let dictKeyArr = dict[key] as! NSArray
var arrM: [Reflect] = []
for (_, value) in dictKeyArr.enumerated() {
let elementModel = elementModelType.parse(dict: value as! NSDictionary)
arrM.append(elementModel)
}
model.setValue(arrM, forKeyPath: name)
}
}
}
}
model.parseOver()
return model
}
class func parseAggregateArray<T>(arrDict: NSArray,basicType: ReflectType.BasicType, ins: T) -> [T]{
var intArrM: [T] = []
if arrDict.count == 0 {return intArrM}
for (_, value) in arrDict.enumerated() {
var element: T = ins
let v = "\(value)"
if T.self is Int.Type {
element = Int(Float(v)!) as! T
}
else if T.self is Float {element = v.floatValue as! T}
else if T.self is Double.Type {element = v.doubleValue as! T}
else if T.self is NSNumber.Type {element = NSNumber(value: v.doubleValue!) as! T}
else if T.self is String.Type {element = v as! T}
else{element = value as! T}
intArrM.append(element)
}
return intArrM
}
func mappingDict() -> [String: String]? {return nil}
func ignorePropertiesForParse() -> [String]? {return nil}
}
|
mit
|
e0d3686099cc978c478e870fdbd2aca0
| 36.242009 | 154 | 0.390755 | 5.983859 | false | false | false | false |
accepton/accepton-apple
|
Pod/Vendor/Alamofire/ServerTrustPolicy.swift
|
1
|
12930
|
// ServerTrustPolicy.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
let policies: [String: ServerTrustPolicy]
/**
Initializes the `ServerTrustPolicyManager` instance with the given policies.
Since different servers and web services can have different leaf certificates, intermediate and even root
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, key
pinning for host3 and disabling evaluation for host4.
- parameter policies: A dictionary of all policies mapped to a particular host.
- returns: The new `ServerTrustPolicyManager` instance.
*/
init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/**
Returns the `ServerTrustPolicy` for the given host if applicable.
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
this method and implement more complex mapping implementations such as wildcards.
- parameter host: The host to use when searching for a matching policy.
- returns: The server trust policy for the given host if found.
*/
func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension NSURLSession {
private struct AssociatedKeys {
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/**
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
Using pinned certificates or keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
to route all communication over an HTTPS connection with pinning enabled.
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
validate the host provided by the challenge. Applications are encouraged to always
validate the host in production environments to guarantee the validity of the server's
certificate chain.
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
considered valid if one of the pinned certificates match one of the server certificates.
By validating both the certificate chain and host, certificate pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- PinPublicKeys: Uses the pinned keys to validate the server trust. The server trust is considered
valid if one of the pinned keys match one of the server certificate keys.
By validating both the certificate chain and host, key pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
*/
enum ServerTrustPolicy {
case PerformDefaultEvaluation(validateHost: Bool)
case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case DisableEvaluation
case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
// MARK: - Bundle Location
/**
Returns all certificates within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `.cer` files.
- returns: All certificates within the given bundle.
*/
static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil)
}.flatten())
for path in paths {
if let
certificateData = NSData(contentsOfFile: path),
certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/**
Returns all keys within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `*.cer` files.
- returns: All keys within the given bundle.
*/
static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificatesInBundle(bundle) {
if let publicKey = publicKeyForCertificate(certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/**
Evaluates whether the server trust is valid for the given host.
- parameter serverTrust: The server trust to evaluate.
- parameter host: The host of the challenge protection space.
- returns: Whether the server trust is valid.
*/
func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .PerformDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
serverTrustIsValid = trustIsValid(serverTrust)
case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData.isEqualToData(pinnedCertificateData) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .DisableEvaluation:
serverTrustIsValid = true
case let .CustomEvaluation(closure):
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType(kSecTrustResultInvalid)
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
let proceed = SecTrustResultType(kSecTrustResultProceed)
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateDataForCertificates(certificates)
}
private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
return certificates.map { SecCertificateCopyData($0) as NSData }
}
// MARK: - Private - Key Extraction
private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let
certificate = SecTrustGetCertificateAtIndex(trust, index),
publicKey = publicKeyForCertificate(certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust where trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
|
mit
|
855d3c1961188f1ec627fb54e70ef294
| 41.807947 | 121 | 0.659653 | 6.080903 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK
|
BridgeAppSDK/SBALearnInfo.swift
|
2
|
3971
|
//
// SBALearnInfo.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
public protocol SBALearnInfo: class {
/**
Access the SBALearnItem objects to show in the Learn tab table view.
@param index The index into the `SBALearnItem` array
@return The learn item
*/
subscript(index: Int) -> SBALearnItem? { get }
/**
See how many SBALearnItem objects to show
@return The count of learn items
*/
var count: Int! { get }
}
extension SBALearnInfo {
/**
Convenience method for getting the `SBALearnItem` for a table or collection using
the `IndexPath`. `IndexPath.section` is ignored.
@param indexPath The index path for the item to get
@return The learnItem at that index path
*/
public func item(at indexPath: IndexPath) -> SBALearnItem? {
guard let item = self[indexPath.item] else {
assertionFailure("no learn item at index \(indexPath.row)")
return nil
}
return item
}
}
/**
`SBALearnInfo` implementation that uses a localizable plist.
*/
public final class SBALearnInfoPList : NSObject, SBALearnInfo {
fileprivate var rowItems: [SBALearnItem]!
public convenience override init() {
self.init(name: "LearnInfo")!
}
public init?(name: String) {
super.init()
guard let plist = SBAResourceFinder.shared.plist(forResource: name) else {
assertionFailure("\(name) plist file not found in the resource bundle")
return nil
}
guard let rowItemsDicts = plist["rowItems"] as? [NSDictionary] else {
assertionFailure("\(name) plist file does not define 'rowItems' (or it does not contain NSDictionary objects)")
return nil
}
self.rowItems = rowItemsDicts.map({ $0 as SBALearnItem }).filter({ $0.isValidLearnItem() })
}
public subscript(index: Int) -> SBALearnItem? {
guard index >= 0 && index < rowItems.count else {
assertionFailure("index \(index) out of bounds (0...\(rowItems.count))")
return nil
}
return rowItems[index]
}
public var count : Int! {
return rowItems.count
}
}
|
bsd-3-clause
|
a193b7b1dd164fbbad0bb4b8853769c3
| 35.759259 | 123 | 0.677834 | 4.643275 | false | false | false | false |
tnantoka/boid
|
Boid/BoidScene.swift
|
1
|
1539
|
//
// BoidScene.swift
// Boid
//
// Created by Tatsuya Tobioka on 9/14/14.
// Copyright (c) 2014 tnantoka. All rights reserved.
//
import SpriteKit
class BoidScene: SKScene {
let numberOfBirds = 10
var birdNodes = [BirdNode]()
var contentCreated = false
let startWithTouch = false
override func didMoveToView(view: SKView) {
self.scaleMode = .AspectFit
if !startWithTouch {
self.createSceneContents()
}
}
func createSceneContents() {
if self.contentCreated {
return
}
let degree: Double = 360.0 / Double(self.numberOfBirds)
let radius = 120.0
for i in 0..<self.numberOfBirds {
let birdNode = BirdNode()
let degree = degree * Double(i)
let radian = Utility.degreeToRadian(degree)
let x = Double(CGRectGetMidX(self.frame)) + cos(radian) * radius
let y = Double(CGRectGetMidY(self.frame)) + sin(radian) * radius
birdNode.position = CGPoint(x: x, y: y)
self.addChild(birdNode)
self.birdNodes.append(birdNode)
}
self.contentCreated = true
}
override func update(currentTime: NSTimeInterval) {
for birdNode in self.birdNodes {
birdNode.update(birdNodes: self.birdNodes, frame: self.frame)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.createSceneContents()
}
}
|
mit
|
1c95f9f5edea337799ed0daae52a83f6
| 25.084746 | 82 | 0.584795 | 4.275 | false | false | false | false |
phatblat/realm-cocoa
|
examples/installation/watchos/swift/XCFrameworkExample/XCFrameworkExample WatchKit Extension/InterfaceController.swift
|
15
|
1598
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import WatchKit
import RealmSwift
class Counter: Object {
@objc dynamic var count = 0
}
class InterfaceController: WKInterfaceController {
@IBOutlet var button: WKInterfaceButton!
let counter: Counter
var token: NotificationToken! = nil
override init() {
counter = Counter()
super.init()
let realm = try! Realm()
try! realm.write {
realm.add(counter)
}
}
@IBAction func increment() {
try! counter.realm!.write { counter.count += 1 }
}
override func willActivate() {
super.willActivate()
token = counter.realm!.observe { [unowned self] _, _ in
self.button.setTitle("\(self.counter.count)")
}
}
override func didDeactivate() {
token.invalidate()
super.didDeactivate()
}
}
|
apache-2.0
|
e342e7eae62819dfbb9021d0880383c9
| 27.535714 | 76 | 0.593242 | 4.857143 | false | false | false | false |
Lclmyname/BookReader_Swift
|
Pods/Fuzi/Fuzi/Document.swift
|
4
|
7610
|
// Document.swift
// Copyright (c) 2015 Ce Zheng
//
// 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 Foundation
import libxml2
/// XML document which can be searched and queried.
open class XMLDocument {
// MARK: - Document Attributes
/// The XML version.
open fileprivate(set) lazy var version: String? = {
return ^-^self.cDocument.pointee.version
}()
/// The string encoding for the document. This is NSUTF8StringEncoding if no encoding is set, or it cannot be calculated.
open fileprivate(set) lazy var encoding: String.Encoding = {
if let encodingName = ^-^self.cDocument.pointee.encoding {
let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!)
if encoding != kCFStringEncodingInvalidId {
return String.Encoding(rawValue: UInt(CFStringConvertEncodingToNSStringEncoding(encoding)))
}
}
return String.Encoding.utf8
}()
// MARK: - Accessing the Root Element
/// The root element of the document.
open fileprivate(set) var root: XMLElement?
// MARK: - Accessing & Setting Document Formatters
/// The formatter used to determine `numberValue` for elements in the document. By default, this is an `NSNumberFormatter` instance with `NSNumberFormatterDecimalStyle`.
open lazy var numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
/// The formatter used to determine `dateValue` for elements in the document. By default, this is an `NSDateFormatter` instance configured to accept ISO 8601 formatted timestamps.
open lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
// MARK: - Creating XML Documents
fileprivate let cDocument: xmlDocPtr
/**
Creates and returns an instance of XMLDocument from an XML string, throwing XMLError if an error occured while parsing the XML.
- parameter string: The XML string.
- parameter encoding: The string encoding.
- throws: `XMLError` instance if an error occurred
- returns: An `XMLDocument` with the contents of the specified XML string.
*/
public convenience init(string: String, encoding: String.Encoding = String.Encoding.utf8) throws {
guard let cChars = string.cString(using: encoding) else {
throw XMLError.invalidData
}
try self.init(cChars: cChars)
}
/**
Creates and returns an instance of XMLDocument from XML data, throwing XMLError if an error occured while parsing the XML.
- parameter data: The XML data.
- throws: `XMLError` instance if an error occurred
- returns: An `XMLDocument` with the contents of the specified XML string.
*/
public convenience init(data: Data) throws {
let cChars = data.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> [CChar] in
let buffer = UnsafeBufferPointer(start: bytes, count: data.count)
return [CChar](buffer)
}
try self.init(cChars: cChars)
}
/**
Creates and returns an instance of XMLDocument from C char array, throwing XMLError if an error occured while parsing the XML.
- parameter cChars: cChars The XML data as C char array
- throws: `XMLError` instance if an error occurred
- returns: An `XMLDocument` with the contents of the specified XML string.
*/
public convenience init(cChars: [CChar]) throws {
let options = Int32(XML_PARSE_NOWARNING.rawValue | XML_PARSE_NOERROR.rawValue | XML_PARSE_RECOVER.rawValue)
try self.init(cChars: cChars, options: options)
}
fileprivate typealias ParseFunction = (UnsafePointer<Int8>?, Int32, UnsafePointer<Int8>?, UnsafePointer<Int8>?, Int32) -> xmlDocPtr?
fileprivate convenience init(cChars: [CChar], options: Int32) throws {
try self.init(parseFunction: { xmlReadMemory($0, $1, $2, $3, $4) }, cChars: cChars, options: options)
}
fileprivate convenience init(parseFunction: ParseFunction, cChars: [CChar], options: Int32) throws {
guard let document = parseFunction(UnsafePointer(cChars), Int32(cChars.count), "", nil, options) else {
throw XMLError.lastError(defaultError: .parserFailure)
}
xmlResetLastError()
self.init(cDocument: document)
}
fileprivate init(cDocument: xmlDocPtr) {
self.cDocument = cDocument
// cDocument shall not be nil
root = XMLElement(cNode: xmlDocGetRootElement(cDocument), document: self)
}
deinit {
xmlFreeDoc(cDocument)
}
// MARK: - XML Namespaces
var defaultNamespaces = [String: String]()
/**
Define a prefix for a default namespace.
- parameter prefix: The prefix name
- parameter ns: The default namespace URI that declared in XML Document
*/
open func definePrefix(_ prefix: String, defaultNamespace ns: String) {
defaultNamespaces[ns] = prefix
}
}
extension XMLDocument: Equatable {}
/**
Determine whether two documents are the same
- parameter lhs: XMLDocument on the left
- parameter rhs: XMLDocument on the right
- returns: whether lhs and rhs are equal
*/
public func ==(lhs: XMLDocument, rhs: XMLDocument) -> Bool {
return lhs.cDocument == rhs.cDocument
}
/// HTML document which can be searched and queried.
open class HTMLDocument: XMLDocument {
// MARK: - Convenience Accessors
/// HTML title of current document
open var title: String? {
return root?.firstChild(tag: "head")?.firstChild(tag: "title")?.stringValue
}
/// HTML head element of current document
open var head: XMLElement? {
return root?.firstChild(tag: "head")
}
/// HTML body element of current document
open var body: XMLElement? {
return root?.firstChild(tag: "body")
}
// MARK: - Creating HTML Documents
/**
Creates and returns an instance of HTMLDocument from C char array, throwing XMLError if an error occured while parsing the HTML.
- parameter cChars: cChars The HTML data as C char array
- throws: `XMLError` instance if an error occurred
- returns: An `HTMLDocument` with the contents of the specified HTML string.
*/
public convenience init(cChars: [CChar]) throws {
let options = Int32(HTML_PARSE_NOWARNING.rawValue | HTML_PARSE_NOERROR.rawValue | HTML_PARSE_RECOVER.rawValue)
try self.init(cChars: cChars, options: options)
}
fileprivate convenience init(cChars: [CChar], options: Int32) throws {
try self.init(parseFunction: { htmlReadMemory($0, $1, $2, $3, $4) }, cChars: cChars, options: options)
}
}
|
mit
|
afe4bc2d14bdab73a48f256e66a79d2f
| 36.121951 | 181 | 0.717871 | 4.336182 | false | false | false | false |
lennet/proNotes
|
app/proNotes/Model/DocumentMetaData.swift
|
1
|
781
|
//
// DocumentMetaData.swift
// proNotes
//
// Created by Leo Thomas on 17/01/16.
// Copyright © 2016 leonardthomas. All rights reserved.
//
import UIKit
class DocumentMetaData: NSObject, NSCoding {
var thumbImage: UIImage?
var fileModificationDate: Date?
override init() {
super.init()
}
private let thumbImageKey = "thumbImage"
required init(coder aDecoder: NSCoder) {
if let imageData = aDecoder.decodeObject(forKey: thumbImageKey) as? Data {
thumbImage = UIImage(data: imageData)
}
}
func encode(with aCoder: NSCoder) {
if let image = thumbImage, let imageData = UIImageJPEGRepresentation(image, 1.0) {
aCoder.encode(imageData, forKey: thumbImageKey)
}
}
}
|
mit
|
cfbf9fd448318cc40559c9e1f5c23da0
| 22.636364 | 90 | 0.639744 | 4.262295 | false | false | false | false |
machelix/PullToMakeFlight
|
PullToMakeFlight/CAKeyframeAnimation+Extensions.swift
|
5
|
2477
|
//
// CAKeyframeAnimation+Extensions.swift
// PullToMakeSoup
//
// Created by Anastasiya Gorban on 4/20/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//
import CoreGraphics
enum AnimationType: String {
case Rotation = "transform.rotation.z"
case Opacity = "opacity"
case TranslationX = "transform.translation.x"
case TranslationY = "transform.translation.y"
case Position = "position"
case PositionY = "position.y"
case ScaleX = "transform.scale.x"
case ScaleY = "transform.scale.y"
}
enum TimingFunction {
case Linear, EaseIn, EaseOut, EaseInEaseOut
}
func mediaTimingFunction(function: TimingFunction) -> CAMediaTimingFunction {
switch function {
case .Linear: return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
case .EaseIn: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
case .EaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
case .EaseInEaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
}
extension CAKeyframeAnimation {
class func animationWith(
type: AnimationType,
values:[AnyObject],
keyTimes:[Double],
duration: Double,
beginTime: Double,
timingFunctions: [TimingFunction] = [TimingFunction.Linear]) -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: type.rawValue)
animation.values = values
animation.keyTimes = keyTimes
animation.duration = duration
animation.beginTime = beginTime
animation.timingFunctions = timingFunctions.map { timingFunction in
return mediaTimingFunction(timingFunction)
}
return animation
}
class func animationPosition(path: CGPath, duration: Double, timingFunction: TimingFunction, beginTime: Double) -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path
animation.duration = duration
animation.beginTime = beginTime
animation.timingFunction = mediaTimingFunction(timingFunction)
return animation
}
}
extension UIView {
func addAnimation(animation: CAKeyframeAnimation) {
layer.addAnimation(animation, forKey: description + animation.keyPath)
layer.speed = 0
}
func removeAllAnimations() {
layer.removeAllAnimations()
}
}
|
mit
|
98151477bc37a6d7dfce35fc9d5107ee
| 31.592105 | 140 | 0.697214 | 5.28145 | false | false | false | false |
bravelocation/yeltzland-ios
|
yeltzland/Model Extensions/Tweet+Date.swift
|
1
|
1379
|
//
// Tweet+Date.swift
// yeltzland
//
// Created by John Pollard on 25/07/2020.
// Copyright © 2020 John Pollard. All rights reserved.
//
import Foundation
extension DisplayTweet {
var timeAgo: String {
get {
let formatter = DateFormatter()
if (self.isToday) {
formatter.dateFormat = "HH:mm"
return "Today\n\(formatter.string(from: self.createdAt))"
}
if Date().dayNumber - self.createdAt.dayNumber < 7 {
formatter.dateFormat = "EEE\nHH:mm"
} else {
formatter.dateFormat = "d MMM\nHH:mm"
}
return formatter.string(from: self.createdAt)
}
}
var accessibilityTimeAgo: String {
// Is the game today?
if (self.isToday) {
let formatter = DateFormatter()
formatter.dateFormat = "HHmm"
return String.init(format: "Today at %@", formatter.string(from: self.createdAt))
} else {
let formatter = DateFormatter()
formatter.dateFormat = "EEE at HHmm"
return formatter.string(from: self.createdAt)
}
}
var isToday: Bool {
// Is the tweet today?
return Date().dayNumber == self.createdAt.dayNumber
}
}
|
mit
|
a845113513aa3dd736e0a33ffe5cf7d6
| 26.56 | 93 | 0.522496 | 4.578073 | false | false | false | false |
FancyPixel/done-swift
|
Done/ViewControllers/ViewController.swift
|
1
|
3110
|
//
// ViewController.swift
// Done
//
// Created by Andrea Mazzini on 28/03/15.
// Copyright (c) 2015 Fancy Pixel. All rights reserved.
//
import Realm
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
@IBOutlet var tableView: UITableView!
var dataSource: RLMResults!
var realmToken: RLMNotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
realmToken = RLMRealm.defaultRealm().addNotificationBlock { note, realm in
self.reloadEntries()
}
reloadEntries()
tableView.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
tableView.tableFooterView = UIView(frame: CGRectZero)
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let container = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 60))
let textField = UITextField(frame: CGRectMake(10, 10, self.view.frame.size.width - 20, 40))
textField.delegate = self
textField.textColor = UIColor.whiteColor()
let placeholer = NSAttributedString(string: "Add an item", attributes: [NSForegroundColorAttributeName: UIColor.lightGrayColor()])
textField.attributedPlaceholder = placeholer
container.addSubview(textField)
return container
}
func reloadEntries() {
dataSource = Entry.allObjects()
self.tableView.reloadData()
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (count(textField.text) == 0) {
return false
}
textField.resignFirstResponder()
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
let entry = Entry()
entry.title = textField.text
entry.completed = false
realm.addObject(entry)
realm.commitWriteTransaction()
reloadEntries()
return true
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(dataSource.count)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
if let entry = dataSource[UInt(indexPath.row)] as? Entry {
cell.textLabel!.text = entry.title
cell.accessoryType = entry.completed ? .Checkmark : .None
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let entry = dataSource[UInt(indexPath.row)] as? Entry {
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
entry.completed = !entry.completed
realm.commitWriteTransaction()
reloadEntries()
}
}
}
|
mit
|
2d0379252777d16145cfab53229fcc0a
| 33.94382 | 138 | 0.656592 | 5.157546 | false | false | false | false |
BumwooPark/RXBattleGround
|
Pods/Carte/Sources/Carte/CarteViewController.swift
|
1
|
4135
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// 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.
#if os(iOS)
import UIKit
open class CarteViewController: UITableViewController {
open lazy var items = Carte.items
open var configureDetailViewController: ((CarteDetailViewController) -> Void)?
override open func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("Open Source Licenses", comment: "Open Source Licenses")
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.navigationController?.viewControllers.count ?? 0 > 1 { // pushed
self.navigationItem.leftBarButtonItem = nil
} else if self.presentingViewController != nil && self.navigationItem.leftBarButtonItem == nil { // presented
self.navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(self.doneButtonDidTap)
)
}
}
open dynamic func doneButtonDidTap() {
self.dismiss(animated: true)
}
}
extension CarteViewController {
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = self.items[indexPath.row]
cell.textLabel?.text = item.displayName
cell.detailTextLabel?.text = item.licenseName
cell.accessoryType = .disclosureIndicator
return cell
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let carteItem = self.items[indexPath.row]
let detailViewController = CarteDetailViewController(item: carteItem)
self.configureDetailViewController?(detailViewController)
self.navigationController?.pushViewController(detailViewController, animated: true)
}
}
open class CarteDetailViewController: UIViewController {
open let carteItem: CarteItem
open var textView: UITextView = {
let textView = UITextView()
textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
textView.font = UIFont.preferredFont(forTextStyle: .footnote)
textView.isEditable = false
textView.alwaysBounceVertical = true
textView.dataDetectorTypes = .link
return textView
}()
public init(item: CarteItem) {
self.carteItem = item
super.init(nibName: nil, bundle: nil)
self.title = item.displayName
self.textView.text = item.licenseText
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func viewDidLoad() {
self.view.backgroundColor = UIColor.white
self.textView.frame = self.view.bounds
self.textView.contentOffset = .zero
self.view.addSubview(self.textView)
}
}
#endif
|
mit
|
7a7428494672807a0379eb91fef7f030
| 36.252252 | 113 | 0.742684 | 4.704209 | false | false | false | false |
Mieraidihaimu/Codility
|
Mier.swift
|
1
|
19219
|
/*
[100%] BinaryGap
Find longest sequence of zeros in binary representation of an integer.
1. A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
*/
public func solution(_ N : Int) -> Int {
// write your code in Swift 3.0 (Linux)
let str = String(N, radix: 2)
var accumuate = 0
var maximum = 0
if str.characters.count < 3 {
return maximum
}
for charact in str.characters{
if charact == "0" {
accumuate += 1
}else{
if accumuate >= maximum {
maximum = accumuate
}
accumuate = 0
}
}
return maximum
}
/*
[100%] OddOccurrencesInArray
Find value that occurs in odd number of elements.
2.1 A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that: [9,3,9,3,9,7,9] -> 7
100/50
*/
/*
77%
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
if A.count < 3{
return A[A.count-1]
}
A = A.sorted()
for index in 0...Int(A.count/2)-1 {
if A[index*2] != A[index*2+1] {
return A[index*2]
}
}
return A[A.count-1]
}
// 100% solution
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
// Return itself if array only contains 1 element
if (A.count == 1) { return A[0] }
var oe = 0
//Since only one odd integer in the array
//so using Xor will balance all the pair numbers except the odd integer
for i in 0 ..< A.count { oe ^= A[i] }
return oe
}
/*
[100%] CyclicRotation
Rotate an array to the right by a given number of steps.
2.2 A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7].
*/
public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
// write your code in Swift 3.0 (Linux)
if K == 0 {
return A
}
if A.count == 0 {
return A
}
if A.count <= K {
return solution(&A, K-A.count)
}
let tem = A[A.count-K...A.count-1]
let asss = A.prefix(upTo: A.count-K)
A = [] + tem + asss
return A
}
/*
[100%] TapeEquilibrium
Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|.
3.1 A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
[5, 6, 2, 4, 1] -> 4
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
if A.count == 2 {
return abs(A[0]-A[1])
}
var accSum = [Int]()
accSum.append(A[0])
for i in 1...A.count-1 {
accSum.append(accSum[i-1]+A[i])
}
var minValue = abs(2*accSum[0]-accSum[accSum.count-1])
for i in 1...A.count-2 {
if minValue > abs(2*accSum[i]-accSum[accSum.count-1]){
minValue = abs(2*accSum[i]-accSum[accSum.count-1])
}
}
return minValue
}
/*
3.2
[100%] FrogJmp
Count minimal number of jumps from position X to Y by D jumping Distance
*/
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
// write your code in Swift 3.0 (Linux)
if X==Y {
return 0
}
if ((Y-X)/D)*D+X < Y {
return ((Y-X)/D + 1)
}
else{
return (Y-X)/D
}
}
/*
3.3
[100%] PermMissingElem
Find the missing element in a given permutation.
A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
if A.count < 1 {
return 1
}
let currentSum = A.reduce(0,{$0+$1})
return ((A.count+1)*(A.count+2)/2) - currentSum
}
/*
4.1
[100%] PermCheck
Check whether array A is a permutation.
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
if A.count < 2 {
if A[0] == 1 {
return 1
}else{
return 0
}
}
var currentSum = 0
var countElement = Array.init(repeating: 0, count: A.count)
for i in 0..<A.count{
currentSum += A[i]
if A.count < A[i] {
return 0
}
countElement[A[i]-1] += 1
if countElement[A[i]-1] > 1 {
return 0
}
}
if ((A.count)*(A.count+1)/2) - currentSum != 0 {
return 0
}
return 1
}
/*
4.2
[100%] FrogRiverOne
Find the earliest time when a frog can jump to the other side of a river.
Task description
A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river
*/
public func solution(_ X : Int, _ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
var counter = Array.init(repeating: 0, count: X)
var counterSum = 0
for i in 0..<A.count{
if A[i] <= X {
if counter[A[i]-1] == 0 {
counter[A[i]-1] += 1
counterSum += 1
}
}
if counterSum == X {
return i
}
}
return -1
}
/*
4.3
[100%] MissingInteger
Find the minimal positive integer not occurring in a given sequence.
that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer (greater than 0) that does not occur in A.
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
var N = [Int: Int]()
for i in 0...A.count-1{
if A[i] > 0 {
N[A[i]] = 1
}
}
if N.isEmpty {
return 1
}
var maximumPositive = 0
for tem in N.keys {
if maximumPositive < tem {
maximumPositive = tem
}
}
for i in 1...maximumPositive{
guard N[i] != nil else {
return i
}
}
return maximumPositive + 1
}
/*
4.3
[100%] 1. MaxCounters
Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.
Task description
You are given N counters, initially set to 0, and you have two possible operations on them:
increase(X) − counter X is increased by 1,
max counter − all counters are set to the maximum value of any counter.
A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:
if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if A[K] = N + 1 then operation K is max counter.
*/
public func solution(_ N : Int, _ A : inout [Int]) -> [Int] {
// write your code in Swift 3.0 (Linux)
let counter = Array.init(repeating: 0, count: N)
var temCounter = counter
var maxCounter = 0
var finalMaxCounter = 0
for eachInt in A{
if eachInt >= 1 && eachInt <= N {
temCounter[eachInt-1] += 1
if temCounter[eachInt-1] > maxCounter {
maxCounter = temCounter[eachInt-1]
}
}else if eachInt == N+1 {
finalMaxCounter += maxCounter
temCounter = counter
maxCounter = 0
}
}
if finalMaxCounter != 0 {
for i in 0...temCounter.count-1{
temCounter[i] += finalMaxCounter
}
}
return temCounter
}
/*
5.1
PassingCars
Count the number of passing cars on the road.
[0 1 0 1 1] -> 5
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
let preSum = prefixSums(A)
var accPair = 0
for index in 0..<A.count{
if A[index] == 0 {
accPair += suffixSums(preSum,positionX: index)
}
}
if accPair > 1000000000 {
return -1
}
return accPair
}
func prefixSums(_ A : [Int]) -> [Int]{
if A.count < 1 {
return []
}
var prefixs = Array.init(repeating: 0, count: A.count+1)
for index in 1..<A.count+1 {
prefixs[index] = A[index-1]+prefixs[index-1]
}
return prefixs
}
func suffixSums(_ P: [Int],positionX x:Int) -> Int{
if x < 0 || x > P.count-1 {
return 0
}
return P[P.count-1] - P[x]
}
/*
5.2
CountDiv
Compute number of integers divisible by k in range [a..b].
3,6,13 -> 3
*/
public func solution(_ A : Int, _ B : Int, _ K : Int) -> Int {
// write your code in Swift 3.0 (Linux)
if A == B{
if A%K == 0 {
return 1
}else{
return 0
}
}else if A%K == 0 {
return B/K - A/K + 1
}else {
return B/K - A/K
}
}
/*
5.3
*/
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
func prefixSums(_ A : [Int]) -> [Int]{
if A.count < 1 {
return []
}
var prefixs = Array.init(repeating: 0, count: A.count+1)
for index in 1..<A.count+1 {
prefixs[index] = A[index-1]+prefixs[index-1]
}
return prefixs
}
func countTotal(_ P: [Int],_ x:Int, _ y:Int) -> Int{
if x < 0 || x > P.count-1 {
return 0
}
if y+1 < x || y+1 > P.count-1 {
return P[P.count-1] - P[x]
}
return P[y+1] - P[x]
}
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
let preSum = prefixSums(A)
var startIndex = 0
let countItem = A.count
if countItem < 3 {
return 0
}
var minSliceAve = Double(preSum[2])/2.0
for index in 0..<countItem-2 {
let fMin = Double(countTotal(preSum, index, index+1))/2.0
let sMin = Double(countTotal(preSum, index, index+2))/3.0
let cMin = min(fMin,sMin)
if minSliceAve-cMin > 0 {
minSliceAve = cMin
startIndex = index
}
}
let fMin = Double(countTotal(preSum, countItem-2, countItem-1))/2.0
if minSliceAve > fMin {
minSliceAve = fMin
startIndex = countItem-2
}
return startIndex
}
/*
5.4
*/
public func translateStringToImpact(_ S: String, _ mode: Int) -> [Int] {
var impactFactor = [Int]()
if mode == 1 {
for charact in S.characters{
if charact=="A" {
impactFactor.append(1)
}else {
impactFactor.append(0)
}
}
}else if mode == 2 {
for charact in S.characters{
if charact=="C" {
impactFactor.append(1)
}else {
impactFactor.append(0)
}
}
}else if mode == 3 {
for charact in S.characters{
if charact=="G" {
impactFactor.append(1)
}else {
impactFactor.append(0)
}
}
}else {
for charact in S.characters{
if charact=="A" {
impactFactor.append(1)
}else if charact=="C" {
impactFactor.append(2)
}else if charact=="G" {
impactFactor.append(3)
}else if charact=="T" {
impactFactor.append(4)
}
}
}
return impactFactor
}
func countTotal(_ P: [Int],_ x:Int, _ y:Int) -> Int{
if x < 0 || x > P.count-1 {
return 0
}
if y+1 < x || y+1 > P.count-1 {
return P[P.count-1] - P[x]
}
return P[y+1] - P[x]
}
public func solution(_ S : inout String, _ P : inout [Int], _ Q : inout [Int]) -> [Int] {
// write your code in Swift 3.0 (Linux)
let onesImpactArray = translateStringToImpact(S,1)
let twosImpactArray = translateStringToImpact(S,2)
let threesImpactArray = translateStringToImpact(S,3)
let preSumOnes = prefixSums(onesImpactArray)
let preSumTwos = prefixSums(twosImpactArray)
let preSumThrees = prefixSums(threesImpactArray)
var mins = [Int]()
for index in 0..<P.count {
if countTotal(preSumOnes, P[index], Q[index]) > 0 {
mins.append(1)
}else if countTotal(preSumTwos, P[index], Q[index]) > 0 {
mins.append(2)
}else if countTotal(preSumThrees, P[index], Q[index]) > 0 {
mins.append(3)
}else {
mins.append(4)
}
}
return mins
}
/*
6.1
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
let sortedA = A.sorted()
let countA = A.count
let foreSolution = sortedA[countA-3]*sortedA[countA-1]*sortedA[countA-2]
let backSolution = sortedA[0]*sortedA[1]*sortedA[countA-1]
if foreSolution > backSolution {
return foreSolution
}
return backSolution
}
/*
6.2
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
let sortedArray = A.sorted()
let countA = sortedArray.count
if countA < 1 {
return 0
}
var result = 1
for index in 1..<countA {
if sortedArray[index] != sortedArray[index-1] {
result += 1
}
}
return result
}
/*
6.3
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
let countA = A.count
if countA < 3 {
return 0
}
let sortedArray = A.sorted()
var result = 0
for index in 1..<countA-1 {
if sortedArray[index] > 0 && sortedArray[index] + sortedArray[index-1] > sortedArray[index+1] {
result = 1
break
}
}
return result
}
/*
To-Be Greater 81%
6.4
*/
func essentialArray(_ A: [Int],_ mode: Int) -> [Int] {
let countCircles = A.count
var essentialA = [Int]()
for index in 0..<countCircles {
essentialA.append(mode*A[index]+index)
}
return essentialA
}
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
let countCircles = A.count
let sortCenterPoint = A
if countCircles < 2 {
return 0
}
let forwardArray = essentialArray(A, 1).sorted
let backwardArray = essentialArray(A,-1).sorted
var counting = 0
for index in 0..<countCircles-1 {
for innerIndex in index+1..<countCircles {
if sortCenterPoint[index]+index >= innerIndex-sortCenterPoint[innerIndex]{
counting += 1
}
}
}
return counting
}
/*
7.1
*/
class customStack {
fileprivate var dataList = [Int]()
func push(_ brackes: Int){
if dataList.count > 0 && dataList[dataList.count-1] < 0 && dataList[dataList.count-1] + brackes == 0 {
dataList.remove(at: dataList.count-1)
return
}
dataList.append(brackes)
}
func isNestedString() -> Bool {
if dataList.count == 0 {
return true
}
return false
}
}
func convertBracketsToIntArray(_ S: String) -> [Int] {
var temArray = [Int]()
for temCharacter in S.characters {
switch temCharacter {
case "(":
temArray.append(-1)
case ")":
temArray.append(1)
case "[":
temArray.append(-2)
case "]":
temArray.append(2)
case "{":
temArray.append(-3)
case "}":
temArray.append(3)
default :
return []
}
}
return temArray
}
public func solution(_ S : inout String) -> Int {
// write your code in Swift 3.0 (Linux)
let len = S.characters.count
if len == 0 {
return 1
}
if len%2 == 1 {
return 0
}
let array = convertBracketsToIntArray(S)
if array.count == 0 {
return 0
}
let aStack = customStack.init()
for value in array {
aStack.push(value)
}
if aStack.isNestedString() {
return 1
}
return 0
}
/*
8.1
91%
Leader
*/
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
class customStack {
fileprivate var dataList = [Int]()
func push(_ number: Int){
if dataList.count > 0 && dataList[dataList.count-1] != number {
dataList.remove(at: dataList.count-1)
return
}
dataList.append(number)
}
func isEmpty() -> Bool {
if dataList.count == 0 {
return true
}
return false
}
func remaining() -> Int {
if dataList.count > 0 {
return dataList[0]
}
return -1
}
}
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
let aStack = customStack.init()
for index in 0..<A.count {
aStack.push(A[index])
}
let value = aStack.remaining()
var countDominate = 0
var returnIndex = -1
for index in 0..<A.count {
if value == A[index] {
countDominate += 1
returnIndex = index
}
}
if countDominate > A.count/2{
return returnIndex
}
return -1
}
/*
9.1
*/
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 3.0 (Linux)
var max_ending = 0
var max_slice = 0
var summary = 0
for temNumber in A {
max_ending = max_ending + temNumber > 0 ? max_ending + temNumber : 0
max_slice = max_slice < max_ending ? max_ending : max_slice
summary += temNumber
}
if max_slice < 1 {
var maxValue = summary
for temNumber in A {
maxValue = temNumber > summary ? temNumber : summary
}
return maxValue
}
return max_slice
}
/*
10.1 100%
CountFactors
Count factors of given number n.
*/
public func solution(_ N : Int) -> Int {
// write your code in Swift 3.0 (Linux)
var i = 2
if N == 1 {
return 1
}
if (N < 4){
return 2
}
var countFacter = 2
while (i*i <= N){
if(N%i == 0){
if (i*i == N){
countFacter += 1
}else {
countFacter += 2
}
}
i += 1
}
return countFacter
}
|
mit
|
e47f0e4b2ce95fd3a1df1b4556a2fc7d
| 22.919054 | 253 | 0.534753 | 3.533297 | false | false | false | false |
1024jp/NSData-GZIP
|
Sources/Gzip/Data+Gzip.swift
|
1
|
9873
|
//
// Data+Gzip.swift
//
/*
The MIT License (MIT)
© 2014-2019 1024jp <wolfrosch.com>
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 Foundation
#if os(Linux)
import zlibLinux
#else
import zlib
#endif
/// Compression level whose rawValue is based on the zlib's constants.
public struct CompressionLevel: RawRepresentable {
/// Compression level in the range of `0` (no compression) to `9` (maximum compression).
public let rawValue: Int32
public static let noCompression = CompressionLevel(Z_NO_COMPRESSION)
public static let bestSpeed = CompressionLevel(Z_BEST_SPEED)
public static let bestCompression = CompressionLevel(Z_BEST_COMPRESSION)
public static let defaultCompression = CompressionLevel(Z_DEFAULT_COMPRESSION)
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public init(_ rawValue: Int32) {
self.rawValue = rawValue
}
}
/// Errors on gzipping/gunzipping based on the zlib error codes.
public struct GzipError: Swift.Error {
// cf. http://www.zlib.net/manual.html
public enum Kind: Equatable {
/// The stream structure was inconsistent.
///
/// - underlying zlib error: `Z_STREAM_ERROR` (-2)
case stream
/// The input data was corrupted
/// (input stream not conforming to the zlib format or incorrect check value).
///
/// - underlying zlib error: `Z_DATA_ERROR` (-3)
case data
/// There was not enough memory.
///
/// - underlying zlib error: `Z_MEM_ERROR` (-4)
case memory
/// No progress is possible or there was not enough room in the output buffer.
///
/// - underlying zlib error: `Z_BUF_ERROR` (-5)
case buffer
/// The zlib library version is incompatible with the version assumed by the caller.
///
/// - underlying zlib error: `Z_VERSION_ERROR` (-6)
case version
/// An unknown error occurred.
///
/// - parameter code: return error by zlib
case unknown(code: Int)
}
/// Error kind.
public let kind: Kind
/// Returned message by zlib.
public let message: String
internal init(code: Int32, msg: UnsafePointer<CChar>?) {
self.message = {
guard let msg = msg, let message = String(validatingUTF8: msg) else {
return "Unknown gzip error"
}
return message
}()
self.kind = {
switch code {
case Z_STREAM_ERROR:
return .stream
case Z_DATA_ERROR:
return .data
case Z_MEM_ERROR:
return .memory
case Z_BUF_ERROR:
return .buffer
case Z_VERSION_ERROR:
return .version
default:
return .unknown(code: Int(code))
}
}()
}
public var localizedDescription: String {
return self.message
}
}
extension Data {
/// Whether the receiver is compressed in gzip format.
public var isGzipped: Bool {
return self.starts(with: [0x1f, 0x8b]) // check magic number
}
/// Create a new `Data` object by compressing the receiver using zlib.
/// Throws an error if compression failed.
///
/// - Parameter level: Compression level.
/// - Returns: Gzip-compressed `Data` object.
/// - Throws: `GzipError`
public func gzipped(level: CompressionLevel = .defaultCompression) throws -> Data {
guard !self.isEmpty else {
return Data()
}
var stream = z_stream()
var status: Int32
status = deflateInit2_(&stream, level.rawValue, Z_DEFLATED, MAX_WBITS + 16, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, Int32(DataSize.stream))
guard status == Z_OK else {
// deflateInit2 returns:
// Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
// Z_MEM_ERROR There was not enough memory.
// Z_STREAM_ERROR A parameter is invalid.
throw GzipError(code: status, msg: stream.msg)
}
var data = Data(capacity: DataSize.chunk)
repeat {
if Int(stream.total_out) >= data.count {
data.count += DataSize.chunk
}
let inputCount = self.count
let outputCount = data.count
self.withUnsafeBytes { (inputPointer: UnsafeRawBufferPointer) in
stream.next_in = UnsafeMutablePointer<Bytef>(mutating: inputPointer.bindMemory(to: Bytef.self).baseAddress!).advanced(by: Int(stream.total_in))
stream.avail_in = uint(inputCount) - uInt(stream.total_in)
data.withUnsafeMutableBytes { (outputPointer: UnsafeMutableRawBufferPointer) in
stream.next_out = outputPointer.bindMemory(to: Bytef.self).baseAddress!.advanced(by: Int(stream.total_out))
stream.avail_out = uInt(outputCount) - uInt(stream.total_out)
status = deflate(&stream, Z_FINISH)
stream.next_out = nil
}
stream.next_in = nil
}
} while stream.avail_out == 0
guard deflateEnd(&stream) == Z_OK, status == Z_STREAM_END else {
throw GzipError(code: status, msg: stream.msg)
}
data.count = Int(stream.total_out)
return data
}
/// Create a new `Data` object by decompressing the receiver using zlib.
/// Throws an error if decompression failed.
///
/// - Returns: Gzip-decompressed `Data` object.
/// - Throws: `GzipError`
public func gunzipped() throws -> Data {
guard !self.isEmpty else {
return Data()
}
var stream = z_stream()
var status: Int32
status = inflateInit2_(&stream, MAX_WBITS + 32, ZLIB_VERSION, Int32(DataSize.stream))
guard status == Z_OK else {
// inflateInit2 returns:
// Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
// Z_MEM_ERROR There was not enough memory.
// Z_STREAM_ERROR A parameters are invalid.
throw GzipError(code: status, msg: stream.msg)
}
var data = Data(capacity: self.count * 2)
repeat {
if Int(stream.total_out) >= data.count {
data.count += self.count / 2
}
let inputCount = self.count
let outputCount = data.count
self.withUnsafeBytes { (inputPointer: UnsafeRawBufferPointer) in
stream.next_in = UnsafeMutablePointer<Bytef>(mutating: inputPointer.bindMemory(to: Bytef.self).baseAddress!).advanced(by: Int(stream.total_in))
stream.avail_in = uint(inputCount) - uInt(stream.total_in)
data.withUnsafeMutableBytes { (outputPointer: UnsafeMutableRawBufferPointer) in
stream.next_out = outputPointer.bindMemory(to: Bytef.self).baseAddress!.advanced(by: Int(stream.total_out))
stream.avail_out = uInt(outputCount) - uInt(stream.total_out)
status = inflate(&stream, Z_SYNC_FLUSH)
stream.next_out = nil
}
stream.next_in = nil
}
} while status == Z_OK
guard inflateEnd(&stream) == Z_OK, status == Z_STREAM_END else {
// inflate returns:
// Z_DATA_ERROR The input data was corrupted (input stream not conforming to the zlib format or incorrect check value).
// Z_STREAM_ERROR The stream structure was inconsistent (for example if next_in or next_out was NULL).
// Z_MEM_ERROR There was not enough memory.
// Z_BUF_ERROR No progress is possible or there was not enough room in the output buffer when Z_FINISH is used.
throw GzipError(code: status, msg: stream.msg)
}
data.count = Int(stream.total_out)
return data
}
}
private struct DataSize {
static let chunk = 1 << 14
static let stream = MemoryLayout<z_stream>.size
private init() { }
}
|
mit
|
836ca057ec5ccebe1a0f30392fa1d2cf
| 32.808219 | 159 | 0.574352 | 4.709924 | false | false | false | false |
ahoppen/swift
|
test/Generics/abstract_type_witnesses_in_protocols.swift
|
2
|
2274
|
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s
protocol P {
associatedtype T
}
struct G<T> : P {}
protocol Q {
associatedtype A : P
}
protocol R {}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q1@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q1]B : P, Self.[Q]A.[P]T == Self.[Q1]B.[P]T>
// GSB: Non-canonical requirement
protocol Q1 : Q {
associatedtype B : P where A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q1a@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q1a]B : P, Self.[Q]A.[P]T : R, Self.[Q]A.[P]T == Self.[Q1a]B.[P]T>
// GSB: Missing requirement
protocol Q1a : Q {
associatedtype B : P where A.T : R, A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q1b@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q1b]B : P, Self.[Q]A.[P]T : R, Self.[Q]A.[P]T == Self.[Q1b]B.[P]T>
// GSB: Non-canonical requirement
protocol Q1b : Q {
associatedtype B : P where B.T : R, A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q2@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q2]B : P, Self.[Q]A.[P]T == Self.[Q2]B.[P]T>
// GSB: Missing requirement
protocol Q2 : Q {
associatedtype B : P where A.T == B.T, A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q3@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q3]B : P, Self.[Q]A.[P]T == Self.[Q3]B.[P]T>
// GSB: Unsupported recursive requirement
protocol Q3 : Q {
associatedtype B : P where A == G<A.T>, A.T == B.T
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q4@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q4]B : P, Self.[Q]A.[P]T == Self.[Q4]B.[P]T>
// GSB: Unsupported recursive requirement
protocol Q4 : Q {
associatedtype B : P where A.T == B.T, A == G<A.T>
}
|
apache-2.0
|
2ba0a74831f696fabb851e16a40ab10c
| 35.095238 | 164 | 0.638083 | 2.587031 | false | false | false | false |
SAP/IssieBoard
|
ConfigurableKeyboard/KeyboardModel.swift
|
1
|
3308
|
import Foundation
var counter = 0
class Keyboard {
var pages: [Page]
init() {
self.pages = []
}
func addKey(key: Key, row: Int, page: Int) {
if self.pages.count <= page {
for i in self.pages.count...page {
self.pages.append(Page())
}
}
self.pages[page].addKey(key, row: row)
}
}
class Page {
var rows: [[Key]]
init() {
self.rows = []
}
func addKey(key: Key, row: Int) {
if self.rows.count <= row {
for i in self.rows.count...row {
self.rows.append([])
}
}
self.rows[row].append(key)
}
}
class Key: Hashable {
enum KeyType {
case Character
case Backspace
case ModeChange
case KeyboardChange
case Space
case Return
case Undo
case Restore
case DismissKeyboard
case CustomCharSetOne
case CustomCharSetTwo
case CustomCharSetThree
case SpecialKeys
case HiddenKey
case Other
}
var type: KeyType
var keyTitle : String?
var keyOutput : String?
var pageNum: Int
var toMode: Int? //if type is ModeChange toMode holds the page it links to
var hasOutput : Bool {return (keyOutput != nil)}
var hasTitle : Bool {return (keyTitle != nil)}
var isCharacter: Bool {
get {
switch self.type {
case
.Character,
.CustomCharSetOne,
.CustomCharSetTwo,
.CustomCharSetThree,
.HiddenKey,
.SpecialKeys:
return true
default:
return false
}
}
}
var isSpecial: Bool {
get {
switch self.type {
case
.Backspace,
.ModeChange,
.KeyboardChange,
.Space,
.DismissKeyboard,
.Return,
.Undo,
.Restore :
return true
default:
return false
}
}
}
var hashValue: Int
init(_ type: KeyType) {
self.type = type
self.hashValue = counter
counter += 1
pageNum = -1
}
convenience init(_ key: Key) {
self.init(key.type)
self.keyTitle = key.keyTitle
self.keyOutput = key.keyOutput
self.toMode = key.toMode
self.pageNum = key.getPage()
}
func setKeyTitle(keyTitle: String) {
self.keyTitle = keyTitle
}
func getKeyTitle () -> String {
if (keyTitle != nil) {
return keyTitle!
}
else {
return ""
}
}
func setKeyOutput(keyOutput: String) {
self.keyOutput = keyOutput
}
func getKeyOutput () -> String {
if (keyOutput != nil) {
return keyOutput!
}
else {
return ""
}
}
func setPage(pageNum : Int) {
self.pageNum = pageNum
}
func getPage() -> Int {
return self.pageNum
}
}
func ==(lhs: Key, rhs: Key) -> Bool {
return lhs.hashValue == rhs.hashValue
}
|
apache-2.0
|
3b9d2bf20de3cdf453192883cc7d104e
| 19.170732 | 78 | 0.472189 | 4.594444 | false | false | false | false |
BMMax/LiveApp_swift
|
LiveApp/LiveApp/MBNetworkTool.swift
|
1
|
870
|
//
// MBNetworkTool.swift
// LiveApp
//
// Created by user on 17/1/11.
// Copyright © 2017年 mobin. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class MBNetworkTool {
class func requestData(_ type: MethodType = .GET, urlString: String, parameters: [String : Any]?, callBack: @escaping (_ error: Error?,_ result: Any?) ->()) {
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(urlString, method: method, parameters: parameters).responseJSON { (respose) in
guard let result = respose.result.value else {
debugPrint("网络错误")
callBack(respose.result.error,nil)
return
}
callBack(nil,result)
}
}
}
|
mit
|
91921adfeab368b3f7076298b6b8f31f
| 22.861111 | 163 | 0.562282 | 4.360406 | false | false | false | false |
Moballo/MOBCore
|
Sources/MOBExtensions.swift
|
2
|
39614
|
//
// MOBExtensions.swift
// MOBCore
//
// Created by Jason Morcos on 12/4/15.
// Copyright © 2017 Moballo, LLC. All rights reserved.
//
#if os(iOS)
import UIKit
import CoreLocation
import MapKit
//EXTENSIONS BEGIN HERE
extension Sequence {
public func toArray() -> [Iterator.Element] {
return Array(self)
}
/// Returns an array with the contents of this sequence, shuffled.
public func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}
extension UITableView {
@objc public func deselectAllCells() {
if self.indexPathsForSelectedRows != nil {
if self.indexPathsForSelectedRows! != [] {
for cell in self.indexPathsForSelectedRows! {
self.deselectRow(at: cell, animated: false)
}
}
}
}
}
extension UINavigationController {
fileprivate func doAfterAnimatingTransition(animated: Bool, completion: @escaping (() -> Void)) {
if let coordinator = transitionCoordinator, animated {
coordinator.animate(alongsideTransition: nil, completion: { _ in
completion()
})
} else {
DispatchQueue.main.async {
completion()
}
}
}
@objc public func pushToViewController(_ viewController: UIViewController, animated:Bool = true, completion: @escaping ()->()) {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.doAfterAnimatingTransition(animated: animated, completion: completion);
}
self.pushViewController(viewController, animated: animated)
CATransaction.commit()
}
@objc public func popViewController(animated:Bool = true, completion: @escaping ()->()) {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.doAfterAnimatingTransition(animated: animated, completion: completion);
}
self.popViewController(animated: true)
CATransaction.commit()
}
@objc public func popToViewController(_ viewController: UIViewController, animated:Bool = true, completion: @escaping ()->()) {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.doAfterAnimatingTransition(animated: animated, completion: completion);
}
self.popToViewController(viewController, animated: animated)
CATransaction.commit()
}
@objc public func popToRootViewController(animated:Bool = true, completion: @escaping ()->()) {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.doAfterAnimatingTransition(animated: animated, completion: completion);
}
self.popToRootViewController(animated: animated)
CATransaction.commit()
}
}
extension NSObject {
///Short-hand function to register a notification observer
public func observeNotification(_ name: String, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: NSNotification.Name(rawValue: name), object: nil)
}
}
extension NSString {
@objc public func stringAtIndex(_ index: Int) -> String {
let char = self.character(at: index)
return "\(Character(UnicodeScalar(char)!))"
}
}
public extension NSNumber {
@objc func degreesToCardinalDirection()->String {
let headingDeg:Double = Double((self.doubleValue + 720.0)).truncatingRemainder(dividingBy: 360)
if(headingDeg > 348.15) {
return "N"
} else if (headingDeg > 326.25) {
return "NNW"
} else if (headingDeg > 303.75) {
return "NW"
} else if (headingDeg > 281.25) {
return "WNW"
} else if (headingDeg > 258.75) {
return "W"
} else if (headingDeg > 236.25) {
return "WSW"
} else if (headingDeg > 213.75) {
return "SW"
} else if (headingDeg > 191.25) {
return "SSW"
} else if (headingDeg > 168.75) {
return "S"
} else if (headingDeg > 146.25) {
return "SSE"
} else if (headingDeg > 123.75) {
return "SE"
} else if (headingDeg > 101.25) {
return "ESE"
} else if (headingDeg > 78.75) {
return "E"
} else if (headingDeg > 56.25) {
return "ENE"
} else if (headingDeg > 33.75) {
return "NE"
} else if (headingDeg > 11.25) {
return "NNE"
}
return "N"
}
}
extension UIView {
@objc public func getViewScreenshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
public static func animateWithDuration(_ duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping damping: CGFloat, animations: @escaping () -> ()) {
UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: 0.0, options: [], animations: animations, completion: nil)
}
public var rootSuperview: UIView {
var view = self
while view.superview != nil {
view = view.superview!
}
return view
}
public var isOnWindow: Bool {
return self.window != nil
}
}
extension UIColor {
public convenience init?(hexString: String) {
let r, g, b, a: CGFloat
if hexString.hasPrefix("#") {
let start = hexString.index(hexString.startIndex, offsetBy: 1)
let hexColor = String(hexString[start...])
if hexColor.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
public convenience init(redInt: Int, greenInt: Int, blueInt: Int, alpha: CGFloat) {
let r = CGFloat(redInt) / 255
let g = CGFloat(greenInt) / 255
let b = CGFloat(blueInt) / 255
self.init(red: r, green: g, blue: b, alpha: alpha)
return
}
public convenience init(redInt: Int, greenInt: Int, blueInt: Int) {
self.init(redInt: redInt, greenInt: greenInt, blueInt: blueInt, alpha: 1.0)
return
}
public var getRed:CGFloat {
get {
if let (red, _, _, _) = self.rgbCGFloat() {
return red
}
return 0.00
}
}
public var getGreen:CGFloat {
get {
if let (_, green, _, _) = self.rgbCGFloat() {
return green
}
return 0.00
}
}
public var getBlue:CGFloat {
get {
if let (_, _, blue, _) = self.rgbCGFloat() {
return blue
}
return 0.00
}
}
public var getAlpha:CGFloat {
get {
if let (_, _, _, alpha) = self.rgbCGFloat() {
return alpha
}
return 0.00
}
}
public func rgbInt() -> (red:Int, green:Int, blue:Int, alpha:Int)? {
var fRed : CGFloat = 0
var fGreen : CGFloat = 0
var fBlue : CGFloat = 0
var fAlpha: CGFloat = 0
if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
let iRed = Int(fRed * 255.0)
let iGreen = Int(fGreen * 255.0)
let iBlue = Int(fBlue * 255.0)
let iAlpha = Int(fAlpha * 255.0)
return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha)
} else {
// Could not extract RGBA components:
return nil
}
}
public func rgbCGFloat() -> (red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat)? {
var fRed : CGFloat = 0
var fGreen : CGFloat = 0
var fBlue : CGFloat = 0
var fAlpha: CGFloat = 0
if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
return (red:fRed, green:fGreen, blue:fBlue, alpha:fAlpha)
} else {
// Could not extract RGBA components:
return nil
}
}
@objc public func darker(_ rate: CGFloat)->UIColor {
if var (red, green, blue, alpha) = self.rgbCGFloat() {
red = max(0.00, red - rate)
green = max(0.00, green - rate)
blue = max(0.00, blue - rate)
alpha = alpha * 1.0//silence annoying "should be a let" error
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
return self
}
@objc public func lighter(_ rate: CGFloat)->UIColor {
return self.darker(-1*rate)
}
}
extension UIImage {
public static func solidColor(_ color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
@objc public func colorize(_ tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()// as CGContextRef
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0);
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
context?.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
UIGraphicsEndImageContext()
return newImage
}
}
extension CLLocationCoordinate2D {
public func isIn(region: MKCoordinateRegion) -> Bool {
let center = region.center
var northWestCorner = center
var southEastCorner = center
northWestCorner.latitude = center.latitude - (region.span.latitudeDelta / 2.0);
northWestCorner.longitude = center.longitude - (region.span.longitudeDelta / 2.0);
southEastCorner.latitude = center.latitude + (region.span.latitudeDelta / 2.0);
southEastCorner.longitude = center.longitude + (region.span.longitudeDelta / 2.0);
if (
self.latitude >= northWestCorner.latitude &&
self.latitude <= southEastCorner.latitude &&
self.longitude >= northWestCorner.longitude &&
self.longitude <= southEastCorner.longitude
)
{
return true
}
return false
}
}
extension MKCoordinateRegion {
public func contains(coordinate: CLLocationCoordinate2D) -> Bool {
return coordinate.isIn(region: self);
}
public func with(padding: CLLocationDegrees) -> MKCoordinateRegion {
var newReg = self
newReg.span.latitudeDelta = padding*2 + newReg.span.latitudeDelta
newReg.span.longitudeDelta = padding*2 + newReg.span.longitudeDelta
return newReg
}
}
extension UIViewController {
public var isModal: Bool {
return self.presentingViewController?.presentedViewController == self
|| (self.navigationController != nil && self.navigationController?.presentingViewController?.presentedViewController == self.navigationController)
|| self.tabBarController?.presentingViewController is UITabBarController
}
}
extension Data {
public func firstBytes(_ length: Int) -> [UInt8] {
var bytes: [UInt8] = [UInt8](repeating: 0, count: length)
(self as NSData).getBytes(&bytes, length: length)
return bytes
}
public var isIcs: Bool {
let signature:[UInt8] = [66, 69, 71, 73]
return firstBytes(4) == signature
}
}
extension UIAlertController {
//does not support text fields
public func duplicate(preferredStyle: UIAlertController.Style? = nil) ->UIAlertController {
let newStyle:UIAlertController.Style
if let overrideStyle = preferredStyle {
newStyle = overrideStyle
} else {
newStyle = self.preferredStyle
}
let newActions = self.actions
let newTitle = self.title
let newMessage = self.message
let newController = UIAlertController(title: newTitle, message: newMessage, preferredStyle: newStyle)
newController.preferredAction = self.preferredAction
for anAction in newActions {
newController.addAction(anAction)
}
return newController
}
}
extension String {
public func minHeight(width: CGFloat, font: UIFont, numberOfLines: Int = 0, lineBreakMode: NSLineBreakMode = NSLineBreakMode.byWordWrapping) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = numberOfLines
label.lineBreakMode = lineBreakMode
label.font = font
label.text = self
label.sizeToFit()
return label.frame.height
}
}
extension UILabel {
@objc public func minHeight() -> CGFloat {
guard let text = self.text else { return 0 }
return text.minHeight(width: self.frame.width, font: self.font, numberOfLines: self.numberOfLines, lineBreakMode: self.lineBreakMode)
}
@objc public func minHeight(forText text: String) -> CGFloat {
return text.minHeight(width: self.frame.width, font: self.font, numberOfLines: self.numberOfLines, lineBreakMode: self.lineBreakMode)
}
}
extension UISearchBar {
public var isEmpty: Bool {
// Returns true if the text is empty or nil
return self.text?.isEmpty ?? true
}
public var magnifyingGlassTextColor:UIColor? {
get {
if let textField = self.textField {
if let glassIconView = textField.leftView as? UIImageView {
return glassIconView.tintColor
}
}
return nil
}
set (newValue) {
if let textField = self.textField {
if let glassIconView = textField.leftView as? UIImageView {
glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate)
glassIconView.tintColor = newValue
}
}
}
}
public var clearButtonTextColor:UIColor? {
get {
if let textField = self.textField {
if let crossIconView = textField.value(forKey: "clearButton") as? UIButton {
return crossIconView.tintColor
}
}
return nil
}
set (newValue) {
if let textField = self.textField {
if let crossIconView = textField.value(forKey: "clearButton") as? UIButton {
crossIconView.setImage(crossIconView.currentImage?.withRenderingMode(.alwaysTemplate), for: .normal)
crossIconView.tintColor = newValue
}
}
}
}
public var placeholderTextColor:UIColor? {
get {
if let textField = self.textField {
if let textFieldInsideSearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel {
return textFieldInsideSearchBarLabel.textColor
}
}
return nil
}
set (newValue) {
if let textField = self.textField {
if let textFieldInsideSearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel {
textFieldInsideSearchBarLabel.textColor = newValue
}
}
}
}
public var font:UIFont? {
get {
if let textField = self.textField {
return textField.font
} else {
return nil
}
}
set (newValue) {
if let textField = self.textField {
textField.font = newValue
}
}
}
public var textColor:UIColor? {
get {
if let textField = self.textField {
return textField.textColor
} else {
return nil
}
}
set (newValue) {
if let textField = self.textField {
textField.textColor = newValue
}
}
}
public var cursorColor:UIColor? {
get {
if let textField = self.textField {
return textField.tintColor
} else {
return nil
}
}
set (newValue) {
if let textField = self.textField {
textField.tintColor = newValue
}
}
}
public var textField: UITextField? {
get {
let svs = subviews.flatMap { $0.subviews }
guard let tf = (svs.filter { $0 is UITextField }).first as? UITextField else { return nil }
return tf
}
}
}
extension UIDevice {
public var isIpad: Bool {
get {
return self.userInterfaceIdiom == UIUserInterfaceIdiom.pad
}
}
public var isIphone: Bool {
get {
return self.userInterfaceIdiom == UIUserInterfaceIdiom.phone
}
}
public var isCarplay: Bool {
get {
return self.userInterfaceIdiom == UIUserInterfaceIdiom.carPlay
}
}
public var isTV: Bool {
get {
return self.userInterfaceIdiom == UIUserInterfaceIdiom.tv
}
}
public var isSimulator: Bool {
get {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}
}
public var buildIsSimulator: Bool {
get {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}
}
public static var modelCode: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
extension UIApplication {
public static func appVersion() -> String {
return Bundle.main.applicationVersionNumber
}
public static func appBuild() -> String {
return Bundle.main.applicationBuildNumber
}
public static func appCopyright(customCopyright: String? = nil) -> String {
let copyrightEntity: String
if let overwriteEntityCopyright = customCopyright {
copyrightEntity = overwriteEntityCopyright
} else {
copyrightEntity = MOBInternalConstants.copyrightEntity
}
let year = Calendar.current.component(.year, from: Date())
return "© "+String(year)+" "+copyrightEntity
}
public static func appInfo(customCopyright: String? = nil, disclosure: String? = nil) -> String {
let copyright = UIApplication.appCopyright(customCopyright: customCopyright)
var infoText = "Version: "+UIApplication.appVersion()+"\nBuild: "+UIApplication.appBuild()+"\n \nContact Us: "+MOBInternalConstants.supportEmail+"\nWebsite: "+MOBInternalConstants.supportWebsite+"\n\n"+copyright
if let realDisclosure = disclosure {
infoText += "\n\n" + realDisclosure
}
return infoText
}
public static var isExtension: Bool {
get {
return Bundle.main.isExtension
}
}
public static var isTestFlight: Bool {
get {
Bundle.main.isTestFlight
}
}
@objc public func getScreenshot() -> UIImage {
let layer = self.getCurrentWindow()?.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer!.frame.size, false, scale)
layer?.render(in: UIGraphicsGetCurrentContext()!)
return UIGraphicsGetImageFromCurrentImageContext()!
}
@objc public func getScreenshotImageData() -> Data {
let image = getScreenshot()
if let toReturn = image.pngData() {
return toReturn
}
else if let toReturn = image.jpegData(compressionQuality: 1.0) {
return toReturn
}
return Data()
}
public static func appAboutController(appName: String, customCopyright: String? = nil, disclosure: String? = nil) ->UIAlertController {
let infoText = UIApplication.appInfo(customCopyright: customCopyright, disclosure: disclosure)
let alertController = UIAlertController(title: appName, message: infoText, preferredStyle: UIAlertController.Style.alert)
let Dismiss = UIAlertAction(title: "Dismiss", style: UIAlertAction.Style.cancel) {
UIAlertAction in
}
alertController.addAction(Dismiss)
return alertController;
}
@objc public func getCurrentWindow() -> UIWindow? {
var presentationWindow: UIWindow? = self.delegate?.window ?? nil
if(presentationWindow != nil) {
return presentationWindow
}
if #available(iOS 13.0, *) {
for scene in self.connectedScenes {
if let windowScene = scene as? UIWindowScene {
for window in windowScene.windows {
presentationWindow = window
if windowScene.activationState == .foregroundActive && presentationWindow?.isKeyWindow == true {
return presentationWindow
}
}
}
}
}
if(presentationWindow == nil) {
presentationWindow = self.keyWindow
}
return presentationWindow
}
}
///Fuzzy comparison funcs
public func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
public func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
public func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l <= r
default:
return !(rhs < lhs)
}
}
#elseif os(watchOS)
import UIKit
#endif
//Shared Extensions
extension String {
public func removingCharacters(in characterSet: CharacterSet) -> String {
return self.components(separatedBy: characterSet).joined()
}
public func countOccurances(ofSubstring string: String) -> Int {
let strCount = self.length - self.replacingOccurrences(of: string, with: "").length
return strCount / string.length
}
public func onlyAlphanumerics(keepSpaces: Bool = false)->String {
var filteringSet = CharacterSet.alphanumerics.inverted
if keepSpaces {
filteringSet.remove(" ")
}
return self.removingCharacters(in: filteringSet)
}
public func substring(from index1: String.Index, to index2: String.Index) -> String {
return String(self[index1..<index2])
}
public func substring(to index: String.Index) -> String {
return String(self[..<index])
}
public func substring(from index: String.Index) -> String {
return String(self[index...])
}
public func asDouble() -> Double? {
return NumberFormatter().number(from: self)?.doubleValue
}
public func dateWithTSquareFormat() -> Date? {
//convert date string to NSDate
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateStyle = .medium
formatter.timeStyle = .short
//correct formatting to match required style
//(Aug 27, 2015 11:27 am) -> (Aug 27, 2015, 11:27 AM)
var dateString = self.replacingOccurrences(of: "pm", with: "PM")
dateString = dateString.replacingOccurrences(of: "am", with: "AM")
for year in 1990...2040 { //add comma after years
dateString = dateString.replacingOccurrences(of: "\(year) ", with: "\(year), ")
}
return formatter.date(from: dateString)
}
public func percentStringAsDouble() -> Double? {
if self.length > 0 {
if let displayedNumber = self.substring(to: self.index(self.endIndex, offsetBy: -1)).asDouble() {
return displayedNumber / 100.0
}
}
return nil
}
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(count, r.lowerBound)),
upper: min(count, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
public func strippedWebsiteForURL() -> String {
///converts "http://www.google.com/search/page/saiojdfghadlsifuhlaisdf" to "google.com"
var stripped = self.replacingOccurrences(of: "http://", with: "")
stripped = stripped.replacingOccurrences(of: "https://", with: "")
stripped = stripped.replacingOccurrences(of: "www.", with: "")
return stripped.components(separatedBy: "/")[0]
}
public func truncate(length: Int, trailing: String? = "") -> String {
if self.length > length {
return self.substring(to: self.index(self.startIndex, offsetBy: length)) + (trailing ?? "")
} else {
return self
}
}
public func cleansed() -> String {
return self.replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\t", with: "").replacingOccurrences(of: "\r", with: "").replacingOccurrences(of: "<o:p>", with: "").replacingOccurrences(of: "</o:p>", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
}
public func trimWhitespace() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
public func withNoTrailingWhitespace() -> String {
return self.trailingTrim(.whitespacesAndNewlines)
}
public func withNoLeadingWhitespace() -> String {
return self.leadingTrim(.whitespacesAndNewlines)
}
public func withNoEdgeWhitespace() -> String {
return self.withNoLeadingWhitespace().withNoTrailingWhitespace()
}
public func trailingTrim(_ characterSet : CharacterSet) -> String {
if let range = rangeOfCharacter(from: characterSet, options: [.anchored, .backwards]) {
return self.substring(to: range.lowerBound).trailingTrim(characterSet)
}
return self
}
public func leadingTrim(_ characterSet : CharacterSet) -> String {
if let range = rangeOfCharacter(from: characterSet, options: [.anchored]) {
return self.substring(from: range.upperBound).leadingTrim(characterSet)
}
return self
}
public var length: Int {
return self.count
}
public var hasWhitespace: Bool {
if self.rangeOfCharacter(from: .whitespacesAndNewlines) != nil {
return true
}
return false
}
public enum RegularExpressions: String {
case phone = "^\\s*(?:\\+?(\\d{1,3}))?([-. (]*(\\d{3})[-. )]*)?((\\d{3})[-. ]*(\\d{2,4})(?:[-.x ]*(\\d+))?)\\s*$"
}
public func isValid(regex: RegularExpressions) -> Bool {
return isValid(regex: regex.rawValue)
}
public func isValid(regex: String) -> Bool {
let matches = range(of: regex, options: .regularExpression)
return matches != nil
}
public func onlyDigits() -> String {
let filtredUnicodeScalars = unicodeScalars.filter{CharacterSet.decimalDigits.contains($0)}
return String(String.UnicodeScalarView(filtredUnicodeScalars))
}
public func generatePhoneUrl() -> URL? {
return URL(string: "tel://"+self.onlyDigits());
}
public func isValidPhone() -> Bool {
return self.isValid(regex: .phone)
}
public func formattedAsPhone() -> String {
let s = self.onlyDigits()
if s.length == 10 {
let s2 = String(format: "(%@) %@-%@",
s.substring(to: s.index(s.startIndex, offsetBy: 3)),
s.substring(from: s.index(s.startIndex, offsetBy: 3), to: s.index(s.startIndex, offsetBy: 6)),
s.substring(from: s.index(s.startIndex, offsetBy: 6))
)
return s2
} else if s.length == 7 {
let s2 = String(format: "%@-%@",
s.substring(to: s.index(s.startIndex, offsetBy: 3)),
s.substring(from: s.index(s.startIndex, offsetBy: 3))
)
return s2
} else if s.length > 10 {
let countryCodeLength = s.length - 10;
let s2 = String(format: "+%@ (%@) %@-%@",
s.substring(to: s.index(s.startIndex, offsetBy: countryCodeLength)),
s.substring(from: s.index(s.startIndex, offsetBy: countryCodeLength), to: s.index(s.startIndex, offsetBy: 3+countryCodeLength)),
s.substring(from: s.index(s.startIndex, offsetBy: 3+countryCodeLength), to: s.index(s.startIndex, offsetBy: 6+countryCodeLength)),
s.substring(from: s.index(s.startIndex, offsetBy: 6+countryCodeLength))
)
return s2
}
return self
}
public func contains(all array: [String]) -> Bool {
for aString in array {
if !self.contains(aString) {
return false
}
}
return true
}
public func contains(any array: [String]) -> Bool {
for aString in array {
if self.contains(aString) {
return true
}
}
return false
}
}
extension Date {
public func formattedFromCompenents(styleAttitude: DateFormatter.Style, year: Bool = false, month: Bool = false, day: Bool = false, hour: Bool = false, minute: Bool = false, second: Bool = false, locale: Locale = Locale.current) -> String {
let long = styleAttitude == .long || styleAttitude == .full
let short = styleAttitude == .short
var comps = ""
if year { comps += long ? "yyyy" : "yy" }
if month { comps += long ? "MMMM" : (short ? "MM" : "MMM") }
if day { comps += long ? "dd" : "dd" }
if hour { comps += long ? "HH" : "H" }
if minute { comps += long ? "mm" : "m" }
if second { comps += long ? "ss" : "s" }
let format = DateFormatter.dateFormat(fromTemplate: comps, options: 00, locale: locale)
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: self)
}
public func shortString() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter.string(from: self) as String
}
public func shortDateString() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .none
return formatter.string(from: self) as String
}
public func mediumDateString() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter.string(from: self) as String
}
public func shortTimeString() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter.string(from: self) as String
}
public func mediumTimeString() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .medium
return formatter.string(from: self) as String
}
public func shortDateNoYearString() -> String {
return self.formattedFromCompenents(styleAttitude: .short, year: false, month: true, day: true)
}
public func mediumDateNoYearString() -> String {
return self.formattedFromCompenents(styleAttitude: .medium, year: false, month: true, day: true)
}
public func longDateNoYearString() -> String {
return self.formattedFromCompenents(styleAttitude: .long, year: false, month: true, day: true)
}
///converts to a "10 seconds ago" / "1 day ago" syntax
public func agoString() -> String {
let deltaTime = -self.timeIntervalSinceNow
//in the past
if deltaTime > 0 {
if deltaTime < 60 {
return "just now"
}
if deltaTime < 3600 { //less than an hour
let amount = Int(deltaTime/60.0)
let plural = amount == 1 ? "" : "s"
return "\(amount) Minute\(plural) Ago"
}
else if deltaTime < 86400 { //less than a day
let amount = Int(deltaTime/3600.0)
let plural = amount == 1 ? "" : "s"
return "\(amount) Hour\(plural) Ago"
}
else if deltaTime < 432000 { //less than five days
let amount = Int(deltaTime/86400.0)
let plural = amount == 1 ? "" : "s"
if amount == 1 {
return "Yesterday"
}
return "\(amount) Day\(plural) Ago"
}
}
//in the future
if deltaTime < 0 {
if deltaTime > -60 {
return "Just Now"
}
if deltaTime > -3600 { //in less than an hour
let amount = -Int(deltaTime/60.0)
let plural = amount == 1 ? "" : "s"
return "In \(amount) Minute\(plural)"
}
else if deltaTime > -86400 { //in less than a day
let amount = -Int(deltaTime/3600.0)
let plural = amount == 1 ? "" : "s"
return "In \(amount) Hour\(plural)"
}
else if deltaTime > -432000 { //in less than five days
let amount = -Int(deltaTime/86400.0)
let plural = amount == 1 ? "" : "s"
if amount == 1 {
return "Tomorrow"
}
return "In \(amount) Day\(plural)"
}
}
let dateString = DateFormatter.localizedString(from: self, dateStyle: .medium, timeStyle: .none)
return "\(dateString)"
}
public var isToday: Bool {
return Calendar.current.isDateInToday(self)
}
public var isYesterday: Bool {
return Calendar.current.isDateInYesterday(self)
}
public var isTomorrow: Bool {
return Calendar.current.isDateInTomorrow(self)
}
public func withoutTime() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: dateFormatter.string(from: self))
}
public func withoutTimeAndYear() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd"
return dateFormatter.date(from: dateFormatter.string(from: self))
}
public func stringLiteralOfDate() -> String {
let dateFormatter = DateFormatter()
let theDateFormat = DateFormatter.Style.short
let theTimeFormat = DateFormatter.Style.long
dateFormatter.dateStyle = theDateFormat
dateFormatter.timeStyle = theTimeFormat
return dateFormatter.string(from: self)
}
public func daysUntil(_ otherDate: Date) -> Int
{
let calendar = Calendar.current
let difference = calendar.dateComponents([.day], from: self, to: otherDate)
return difference.day!
}
public func isSameDay(as otherDate: Date) -> Bool {
let order = Calendar.current.compare(self, to: otherDate, toGranularity: .day)
switch order {
case .orderedSame:
return true
default:
return false
}
}
}
extension Array {
///Shuffles the contents of this collection
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}
extension Int {
///Converts an integer to a standardized three-character string. 1 -> 001. 99 -> 099. 123 -> 123.
public func threeCharacterString() -> String {
let start = "\(self)"
let length = start.length
if length == 1 { return "00\(start)" }
else if length == 2 { return "0\(start)" }
else { return start }
}
}
extension Bundle {
public var applicationVersionNumber: String {
if let version = self.infoDictionary?["CFBundleShortVersionString"] as? String {
return version
}
return "Version Number Not Available"
}
public var applicationBuildNumber: String {
if let build = self.infoDictionary?["CFBundleVersion"] as? String {
return build
}
return "Build Number Not Available"
}
public var isExtension: Bool {
get {
return self.bundlePath.hasSuffix(".appex")
}
}
public var isTestFlight: Bool {
get {
if let url = self.appStoreReceiptURL {
return (url.lastPathComponent == "sandboxReceipt")
}
return false
}
}
}
|
mit
|
e7675e2d9e1c91d49661d5f9e466a43c
| 34.590296 | 279 | 0.573715 | 4.74452 | false | false | false | false |
Eonil/JSON.Swift
|
Tests/AllTests/TestAll.swift
|
1
|
4385
|
//
// EonilJSONTests.swift
// EonilJSONTests
//
// Created by Hoon H. on 2016/06/05.
// Copyright © 2016 Eonil. All rights reserved.
//
import XCTest
@testable import EonilJSON
class EonilJSONTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func testJSONSerializerFragmentSupport() throws {
// let a = "AAA"
// let b = try JSONSerialization.data(withJSONObject: a, options: .prettyPrinted)
// let c = try JSONSerialization.jsonObject(with: b, options: .allowFragments)
// XCTAssertTrue(c is NSString)
// let c1 = c as? NSString as? String
// XCTAssertNotNil(c1)
// XCTAssertEqual(a, c1!)
// }
func testGoodNumberValue1() {
let a = Float64(11.11)
do {
let b = try JSONNumber(a)
XCTAssertNotNil(b.float64)
XCTAssertEqual(a, b.float64)
}
catch let e {
XCTFail("\(e)")
}
}
func testBadNumberValue1() {
let a = Float64.nan
XCTAssertThrowsError(try JSONNumber(a))
}
func testBadNumberValue2() {
let a = -Float64.nan
XCTAssertThrowsError(try JSONNumber(a))
}
func testBadNumberValue3() {
let a = Float64.infinity
XCTAssertThrowsError(try JSONNumber(a))
}
func testBadNumberValue4() {
let a = -Float64.infinity
XCTAssertThrowsError(try JSONNumber(a))
}
func testBadNumberValue5() {
let a = Float64(bitPattern: UInt64(0x0000000000000001))
let b = Float64(bitPattern: UInt64(0x000fffffffffffff))
XCTAssertThrowsError(try JSONNumber(a))
XCTAssertThrowsError(try JSONNumber(b))
}
// func testExample() {
// // This is an example of a functional test case.
// // Use XCTAssert and related functions to verify your tests produce the correct results.
// }
//
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measureBlock {
// // Put the code you want to measure the time of here.
// }
// }
/*
func test1() throws {
let a1 = "{ \"aaa\" : 123 }"
let a2 = a1.data(using: String.Encoding.utf8, allowLossyConversion: false)!
let a3 = try JSON.deserialize(a2)
let a4 = JSONValue.object([
"aaa" : JSONValue.number(JSONNumber.int64(123))
])
XCTAssert(a3 == a4)
}
func test2() throws {
let d1 = "This is a dynamic text." as JSONValue
let a1 = [
"aaa" : nil,
"bbb" : true,
"ccc" : 123,
"ddd" : 456.789,
"eee" : d1,
"fff" : [d1, d1, d1],
"ggg" : [
"f1" : d1,
"f2" : d1,
"f3" : d1,
],
] as JSONValue
let a2 = try JSON.serialize(a1)
print(a2)
let a3 = try JSON.deserialize(a2)
print(a3)
XCTAssert(a3 == a1)
print(a3.object!["aaa"]!)
// let v1 = a3.object!["aaa"]!
XCTAssert(a3.object!["aaa"]! == nil)
XCTAssert(a3.object!["fff"]! == [d1, d1, d1])
}
*/
}
///// MARK:
//extension RFC4627 {
// struct Test {
// static func run() throws {
// func tx(c:() throws ->()) throws {
// try c()
// }
//
// try tx {
// }
// try tx {
//// let a1 = [
//// "aaa" : nil,
//// "bbb" : true,
//// "ccc" : 123,
//// "ddd" : 456.789,
//// "eee" : "Here be a dragon.",
//// "fff" : ["xxx", "yyy", "zzz"],
//// "ggg" : [
//// "f1" : "v1",
//// "f2" : "v2",
//// "f3" : "v3",
//// ],
//// ] as Value
////
//// print(a1.object!["aaa"]!)
////// let v1 = a1.object!["aaa"]!
//// assert(a1.object!["aaa"]! == nil)
////
//// let a2 = try JSON.serialize(a1)!
//// print(a2)
////
//// let a3 = try JSON.deserialize(a2)!
//// print(a3)
////
//// assert(a3 == a1)
// }
//
// try tx {
//
// }
//
// }
// }
//}
//
//
//
//
|
mit
|
937601b3d4107c52b5625285745a7fe9
| 21.030151 | 111 | 0.506387 | 3.245004 | false | true | false | false |
nextcloud/ios
|
iOSClient/Viewer/NCViewerMedia/NCPlayer/NCSubtitle/NCSubtitlePlayer.swift
|
1
|
17700
|
//
// NCSubtitlePlayer.swift
// Nextcloud
//
// Created by Federico Malagoni on 18/02/22.
// Copyright © 2022 Federico Malagoni. All rights reserved.
// Copyright © 2022 Marino Faggiana All rights reserved.
//
// Author Federico Malagoni <federico.malagoni@astrairidium.com>
// Author Marino Faggiana <marino.faggiana@nextcloud.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import AVKit
import NextcloudKit
extension NCPlayer {
private struct AssociatedKeys {
static var FontKey = "FontKey"
static var ColorKey = "FontKey"
static var SubtitleKey = "SubtitleKey"
static var SubtitleContainerViewKey = "SubtitleContainerViewKey"
static var SubtitleContainerViewHeightKey = "SubtitleContainerViewHeightKey"
static var SubtitleHeightKey = "SubtitleHeightKey"
static var SubtitleWidthKey = "SubtitleWidthKey"
static var SubtitleContainerViewWidthKey = "SubtitleContainerViewWidthKey"
static var SubtitleBottomKey = "SubtitleBottomKey"
static var PayloadKey = "PayloadKey"
}
private var widthProportion: CGFloat {
return 0.9
}
private var bottomConstantPortrait: CGFloat {
get {
if UIDevice.current.hasNotch {
return -60
} else {
return -40
}
} set {
_ = newValue
}
}
private var bottomConstantLandscape: CGFloat {
get {
if UIDevice.current.hasNotch {
return -120
} else {
return -100
}
} set {
_ = newValue
}
}
var subtitleContainerView: UIView? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewKey) as? UIView }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)}
}
var subtitleLabel: UILabel? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleKey) as? UILabel }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var subtitleLabelHeightConstraint: NSLayoutConstraint? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey) as? NSLayoutConstraint }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var subtitleContainerViewHeightConstraint: NSLayoutConstraint? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewHeightKey) as? NSLayoutConstraint }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewHeightKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var subtitleLabelBottomConstraint: NSLayoutConstraint? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleBottomKey) as? NSLayoutConstraint }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleBottomKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var subtitleLabelWidthConstraint: NSLayoutConstraint? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleWidthKey) as? NSLayoutConstraint }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleWidthKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var subtitleContainerViewWidthConstraint: NSLayoutConstraint? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewWidthKey) as? NSLayoutConstraint }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewWidthKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var parsedPayload: NSDictionary? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.PayloadKey) as? NSDictionary }
set (value) { objc_setAssociatedObject(self, &AssociatedKeys.PayloadKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
func setUpForSubtitle() {
self.subtitleUrls.removeAll()
if let url = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) {
let enumerator = FileManager.default.enumerator(atPath: url)
let filePaths = (enumerator?.allObjects as? [String])
if let filePaths = filePaths {
let txtFilePaths = (filePaths.filter { $0.contains(".srt") }).sorted {
guard let str1LastChar = $0.dropLast(4).last, let str2LastChar = $1.dropLast(4).last else {
return false
}
return str1LastChar < str2LastChar
}
for txtFilePath in txtFilePaths {
let subtitleUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: txtFilePath))
self.subtitleUrls.append(subtitleUrl)
}
}
}
let (all, existing) = NCManageDatabase.shared.getSubtitles(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
if !existing.isEmpty {
for subtitle in existing {
let subtitleUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(subtitle.ocId, fileNameView: subtitle.fileName))
self.subtitleUrls.append(subtitleUrl)
}
}
if all.count != existing.count {
let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_subtitle_not_dowloaded_")
NCContentPresenter.shared.showInfo(error: error)
}
self.setSubtitleToolbarIcon(subtitleUrls: subtitleUrls)
self.hideSubtitle()
}
func setSubtitleToolbarIcon(subtitleUrls: [URL]) {
if subtitleUrls.isEmpty {
playerToolBar?.subtitleButton.isHidden = true
} else {
playerToolBar?.subtitleButton.isHidden = false
}
}
func addSubtitlesTo(_ vc: UIViewController, _ playerToolBar: NCPlayerToolBar?) {
addSubtitleLabel(vc, playerToolBar)
NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
}
func loadText(filePath: URL, _ completion: @escaping (_ contents: String?) -> Void) {
DispatchQueue.global().async {
guard let data = try? Data(contentsOf: filePath),
let encoding = NCUtility.shared.getEncondingDataType(data: data) else {
return
}
if let decodedString = String(data: data, encoding: encoding) {
completion(decodedString)
} else {
completion(nil)
}
}
}
func open(fileFromLocal url: URL) {
subtitleLabel?.text = ""
self.loadText(filePath: url) { contents in
guard let contents = contents else {
return
}
DispatchQueue.main.async {
self.subtitleLabel?.text = ""
self.show(subtitles: contents)
}
}
}
@objc public func hideSubtitle() {
self.subtitleLabel?.isHidden = true
self.subtitleContainerView?.isHidden = true
self.currentSubtitle = nil
}
@objc public func showSubtitle(url: URL) {
self.subtitleLabel?.isHidden = false
self.subtitleContainerView?.isHidden = false
self.currentSubtitle = url
}
private func show(subtitles string: String) {
parsedPayload = try? NCSubtitles.parseSubRip(string)
if let parsedPayload = parsedPayload {
addPeriodicNotification(parsedPayload: parsedPayload)
}
}
private func showByDictionary(dictionaryContent: NSMutableDictionary) {
parsedPayload = dictionaryContent
if let parsedPayload = parsedPayload {
addPeriodicNotification(parsedPayload: parsedPayload)
}
}
func addPeriodicNotification(parsedPayload: NSDictionary) {
// Add periodic notifications
let interval = CMTimeMake(value: 1, timescale: 60)
self.player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in
guard let strongSelf = self, let label = strongSelf.subtitleLabel, let containerView = strongSelf.subtitleContainerView else {
return
}
DispatchQueue.main.async {
label.text = NCSubtitles.searchSubtitles(strongSelf.parsedPayload, time.seconds)
strongSelf.adjustViewWidth(containerView: containerView)
strongSelf.adjustLabelHeight(label: label)
}
}
}
@objc private func deviceRotated(_ notification: Notification) {
guard let label = self.subtitleLabel,
let containerView = self.subtitleContainerView else { return }
DispatchQueue.main.async {
self.adjustViewWidth(containerView: containerView)
self.adjustLabelHeight(label: label)
self.adjustLabelBottom(label: label)
containerView.layoutIfNeeded()
label.layoutIfNeeded()
}
}
private func adjustLabelHeight(label: UILabel) {
let baseSize = CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)
let rect = label.sizeThatFits(baseSize)
if label.text != nil {
self.subtitleLabelHeightConstraint?.constant = rect.height + 5.0
} else {
self.subtitleLabelHeightConstraint?.constant = rect.height
}
}
private func adjustLabelBottom(label: UILabel) {
var bottomConstant: CGFloat = bottomConstantPortrait
switch UIApplication.shared.statusBarOrientation {
case .portrait:
bottomConstant = bottomConstantLandscape
case .landscapeLeft, .landscapeRight, .portraitUpsideDown:
bottomConstant = bottomConstantPortrait
default:
()
}
subtitleLabelBottomConstraint?.constant = bottomConstant
}
private func adjustViewWidth(containerView: UIView) {
let widthConstant: CGFloat = UIScreen.main.bounds.width * widthProportion
subtitleContainerViewWidthConstraint!.constant = widthConstant
subtitleLabel?.preferredMaxLayoutWidth = (widthConstant - 20)
}
fileprivate func addSubtitleLabel(_ vc: UIViewController, _ playerToolBar: NCPlayerToolBar?) {
guard subtitleLabel == nil,
subtitleContainerView == nil else {
return
}
subtitleContainerView = UIView()
subtitleLabel = UILabel()
subtitleContainerView?.translatesAutoresizingMaskIntoConstraints = false
subtitleContainerView?.layer.cornerRadius = 5.0
subtitleContainerView?.layer.masksToBounds = true
subtitleContainerView?.layer.shouldRasterize = true
subtitleContainerView?.layer.rasterizationScale = UIScreen.main.scale
subtitleContainerView?.backgroundColor = UIColor.black.withAlphaComponent(0.35)
subtitleLabel?.translatesAutoresizingMaskIntoConstraints = false
subtitleLabel?.textAlignment = .center
subtitleLabel?.numberOfLines = 0
let fontSize = UIDevice.current.userInterfaceIdiom == .pad ? 38.0 : 20.0
subtitleLabel?.font = UIFont.incosolataMedium(size: fontSize)
subtitleLabel?.lineBreakMode = .byWordWrapping
subtitleLabel?.textColor = .white
subtitleLabel?.backgroundColor = .clear
subtitleContainerView?.addSubview(subtitleLabel!)
var isFound = false
for v in vc.view.subviews where v is UIScrollView {
if let scrollView = v as? UIScrollView {
for subView in scrollView.subviews where subView is imageVideoContainerView {
subView.addSubview(subtitleContainerView!)
isFound = true
break
}
}
}
if !isFound {
vc.view.addSubview(subtitleContainerView!)
}
NSLayoutConstraint.activate([
subtitleLabel!.centerXAnchor.constraint(equalTo: subtitleContainerView!.centerXAnchor),
subtitleLabel!.centerYAnchor.constraint(equalTo: subtitleContainerView!.centerYAnchor)
])
subtitleContainerViewHeightConstraint = NSLayoutConstraint(item: subtitleContainerView!, attribute: .height, relatedBy: .equal, toItem: subtitleLabel!, attribute: .height, multiplier: 1.0, constant: 0.0)
vc.view?.addConstraint(subtitleContainerViewHeightConstraint!)
var bottomConstant: CGFloat = bottomConstantPortrait
switch UIApplication.shared.statusBarOrientation {
case .portrait, .portraitUpsideDown:
bottomConstant = bottomConstantLandscape
case .landscapeLeft, .landscapeRight:
bottomConstant = bottomConstantPortrait
default:
()
}
let widthConstant: CGFloat = UIScreen.main.bounds.width * widthProportion
NSLayoutConstraint.activate([
subtitleContainerView!.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor)
])
subtitleContainerViewWidthConstraint = NSLayoutConstraint(item: subtitleContainerView!, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil,
attribute: .width, multiplier: 1, constant: widthConstant)
// setting default width == 0 because there is no text inside of the label
subtitleLabelWidthConstraint = NSLayoutConstraint(item: subtitleLabel!, attribute: .width, relatedBy: .equal, toItem: subtitleContainerView,
attribute: .width, multiplier: 1, constant: -20)
subtitleLabelBottomConstraint = NSLayoutConstraint(item: subtitleContainerView!, attribute: .bottom, relatedBy: .equal, toItem: vc.view, attribute:
.bottom, multiplier: 1, constant: bottomConstant)
vc.view?.addConstraint(subtitleContainerViewWidthConstraint!)
vc.view?.addConstraint(subtitleLabelWidthConstraint!)
vc.view?.addConstraint(subtitleLabelBottomConstraint!)
}
internal func showAlertSubtitles() {
let alert = UIAlertController(title: nil, message: NSLocalizedString("_subtitle_", comment: ""), preferredStyle: .actionSheet)
for url in subtitleUrls {
print("Play Subtitle at:\n\(url.path)")
let videoUrlTitle = self.metadata.fileName.alphanumeric.dropLast(3)
let subtitleUrlTitle = url.lastPathComponent.alphanumeric.dropLast(3)
var titleSubtitle = String(subtitleUrlTitle.dropFirst(videoUrlTitle.count))
if titleSubtitle.isEmpty {
titleSubtitle = NSLocalizedString("_subtitle_", comment: "")
}
let action = UIAlertAction(title: titleSubtitle, style: .default, handler: { [self] _ in
if NCUtilityFileSystem.shared.getFileSize(filePath: url.path) > 0 {
self.open(fileFromLocal: url)
if let viewController = viewController {
self.addSubtitlesTo(viewController, self.playerToolBar)
self.showSubtitle(url: url)
}
} else {
let alertError = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_subtitle_not_found_", comment: ""), preferredStyle: .alert)
alertError.addAction(UIKit.UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: nil))
viewController?.present(alertError, animated: true, completion: nil)
}
})
alert.addAction(action)
if currentSubtitle == url {
action.setValue(true, forKey: "checked")
}
}
let disable = UIAlertAction(title: NSLocalizedString("_disable_", comment: ""), style: .default, handler: { _ in
self.hideSubtitle()
})
alert.addAction(disable)
if currentSubtitle == nil {
disable.setValue(true, forKey: "checked")
}
alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: { _ in
}))
alert.popoverPresentationController?.sourceView = self.viewController?.view
self.viewController?.present(alert, animated: true, completion: nil)
}
}
|
gpl-3.0
|
ecf78be9a5477dd3b4c63033c696051a
| 42.484029 | 211 | 0.656232 | 5.343599 | false | false | false | false |
tavultesoft/keymanweb
|
ios/engine/KMEI/KeymanEngine/Classes/ResourceDownloadStatusToolbar.swift
|
1
|
5107
|
//
// ResourceDownloadStatusToolbar.swift
// KeymanEngine
//
// Created by Joshua Horton on 8/14/19.
// Copyright © 2019 SIL International. All rights reserved.
//
import Foundation
import UIKit
public class ResourceDownloadStatusToolbar: UIToolbar {
private var statusLabel: UILabel?
private var activityIndicator: UIActivityIndicatorView?
private var actionButton: UIButton?
private var _navigationController: UINavigationController?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
// Only here because it's required by Swift.
required init?(coder: NSCoder) {
super.init(coder: coder)
}
public var navigationController: UINavigationController? {
get {
return _navigationController
}
set {
_navigationController = newValue
}
}
private func setup() {
barTintColor = Colors.statusToolbar
}
/**
* Creates a simple text label for indicating current status without allowing interactivity.
*/
private func setupStatusLabel() -> UILabel {
let labelFrame = CGRect(origin: frame.origin,
size: CGSize(width: frame.width * 0.95,
height: frame.height * 0.7))
let label = UILabel(frame: labelFrame)
label.backgroundColor = UIColor.clear
label.textColor = UIColor.white
label.textAlignment = .center
label.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
label.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin,
.flexibleBottomMargin, .flexibleWidth, .flexibleHeight]
return label
}
/**
* Creates the classic spinning-wheel 'activity in progress' indicator.
*/
private func setupActivityIndicator() -> UIActivityIndicatorView {
let indicatorView = UIActivityIndicatorView(style: .gray)
indicatorView.center = CGPoint(x: frame.width - indicatorView.frame.width,
y: frame.height * 0.5)
indicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleBottomMargin]
indicatorView.startAnimating()
return indicatorView
}
private func setupActionButton(_ text: String, for handler: Any?, onClick: Selector) -> UIButton {
let button = UIButton(type: .roundedRect)
button.addTarget(handler, action: onClick, for: .touchUpInside)
button.frame = CGRect(x: frame.origin.x, y: frame.origin.y,
width: frame.width * 0.95, height: frame.height * 0.7)
button.center = CGPoint(x: frame.width / 2, y: frame.height / 2)
button.tintColor = Colors.statusResourceUpdateButton
button.setTitleColor(UIColor.white, for: .normal)
button.setTitle(text, for: .normal)
button.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin,
.flexibleBottomMargin, .flexibleWidth, .flexibleHeight]
return button
}
private func clearSubviews() {
statusLabel?.removeFromSuperview()
activityIndicator?.removeFromSuperview()
actionButton?.removeFromSuperview()
}
public func displayStatus(_ text: String, withIndicator: Bool, duration: TimeInterval? = nil) {
clearSubviews()
statusLabel = setupStatusLabel()
statusLabel!.text = text
addSubview(statusLabel!)
if withIndicator {
activityIndicator = setupActivityIndicator()
addSubview(activityIndicator!)
}
// Automatically display if we're hidden and have access to our owning UINavigationController.
if navigationController?.isToolbarHidden ?? false {
navigationController!.setToolbarHidden(false, animated: true)
}
if let timeout = duration {
hideAfterDelay(timeout: timeout)
}
}
public func displayButton(_ text: String, with target: Any?, callback: Selector) {
clearSubviews()
// This forces iOS to create any intervening default UIToolbar subviews that may exist by default.
// Anything added afterward will be placed on top of those, enabling interactivity.
layoutIfNeeded()
actionButton = setupActionButton(text, for: target, onClick: callback)
addSubview(actionButton!)
bringSubviewToFront(actionButton!)
// Automatically display if we're hidden and have access to our owning UINavigationController.
if navigationController?.isToolbarHidden ?? false {
navigationController!.setToolbarHidden(false, animated: true)
}
}
private func hideAfterDelay(timeout: TimeInterval) {
Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(self.delayedHide),
userInfo: nil, repeats: false)
}
@objc private func delayedHide() {
// If the navigation controller exists and the toolbar is not hidden. The ! + true literal together
// give false for the condition when the navigation controller does not exist.
if !(navigationController?.isToolbarHidden ?? true) {
navigationController!.setToolbarHidden(true, animated: true)
}
}
}
|
apache-2.0
|
c174ebd05c3c0b142735759afd97ad81
| 33.734694 | 104 | 0.688602 | 5.070506 | false | false | false | false |
Touchwonders/veggies
|
Veggies/SpriteKit/Nodes/Dot.swift
|
1
|
2357
|
//
// Dot.swift
// Veggies
//
// Created by RHLJH Hooijmans on 22/08/15.
// Copyright © 2015 Robert-Hein Hooijmans. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
protocol DotDelegate: class {
func tappedDot(dot: Dot)
}
class Dot: SKSpriteNode {
weak var delegate: DotDelegate?
var imageIndex: Int = 0
var initialRadius: CGFloat = 0.0
var multiplier: Int = 0
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(radius: CGFloat, index: Int){
super.init(texture: SKTexture(imageNamed: "veggie\(index)"), color: .blackColor(), size: CGSizeMake(radius * 2.0, radius * 2.0))
imageIndex = index
initialRadius = radius
let randomValue = CGFloat(Int(arc4random()) % 100) / 100.0
name = Statics.Nodes.Dot
userInteractionEnabled = true
physicsBody = SKPhysicsBody(circleOfRadius: radius + 1.0)
if let physicsBody = physicsBody {
physicsBody.dynamic = true
physicsBody.usesPreciseCollisionDetection = false
physicsBody.allowsRotation = true
physicsBody.pinned = false
physicsBody.resting = false
physicsBody.friction = 0.01
physicsBody.restitution = 0.1
physicsBody.linearDamping = randomValue * 10.0
physicsBody.angularDamping = 0.01
physicsBody.mass = randomValue
physicsBody.affectedByGravity = true
}
}
func addToShoppingList() -> SKAction {
multiplier = multiplier == 0 ? 1 : 0
let initialScale: CGFloat = xScale
let duration: NSTimeInterval = 0.2
let scale: CGFloat = 1.0 + (CGFloat(multiplier) * 0.5)
let growToNewScale = SKAction.customActionWithDuration(duration) { (node, elapsedTime) -> Void in
let t: CGFloat = elapsedTime / CGFloat(duration)
let p: CGFloat = t * t
let s: CGFloat = initialScale * (1.0 - p) + scale * p
node.setScale(s)
}
return growToNewScale
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
delegate?.tappedDot(self)
}
}
|
mit
|
50777be9fc74e95b00dcadf5ca1ad8fe
| 27.743902 | 136 | 0.59253 | 4.646943 | false | false | false | false |
khizkhiz/swift
|
test/expr/cast/dictionary_bridge.swift
|
1
|
4940
|
// RUN: %target-parse-verify-swift
// REQUIRES: objc_interop
class Root : Hashable {
var hashValue: Int {
return 0
}
}
func ==(x: Root, y: Root) -> Bool { return true }
class ObjC : Root {
var x = 0
}
class DerivesObjC : ObjC { }
struct BridgedToObjC : Hashable, _ObjectiveCBridgeable {
static func _isBridgedToObjectiveC() -> Bool {
return true
}
static func _getObjectiveCType() -> Any.Type {
return ObjC.self
}
func _bridgeToObjectiveC() -> ObjC {
return ObjC()
}
static func _forceBridgeFromObjectiveC(
x: ObjC,
result: inout BridgedToObjC?
) {
}
static func _conditionallyBridgeFromObjectiveC(
x: ObjC,
result: inout BridgedToObjC?
) -> Bool {
return true
}
var hashValue: Int {
return 0
}
}
func ==(x: BridgedToObjC, y: BridgedToObjC) -> Bool { return true }
func testUpcastBridge() {
var dictRR = Dictionary<Root, Root>()
var dictRO = Dictionary<Root, ObjC>()
var dictOR = Dictionary<ObjC, Root>()
var dictOO = Dictionary<ObjC, ObjC>()
var dictOD = Dictionary<ObjC, DerivesObjC>()
var dictDO = Dictionary<DerivesObjC, ObjC>()
var dictDD = Dictionary<DerivesObjC, DerivesObjC>()
var dictBB = Dictionary<BridgedToObjC, BridgedToObjC>()
var dictBO = Dictionary<BridgedToObjC, ObjC>()
var dictOB = Dictionary<ObjC, BridgedToObjC>()
// Upcast to object types.
dictRR = dictBB
dictRR = dictBO
dictRR = dictOB
dictRO = dictBB
dictRO = dictBO
dictRO = dictOB
dictOR = dictBB
dictOR = dictBO
dictOR = dictOB
dictOO = dictBB
dictOO = dictBO
dictOO = dictOB
// Upcast key or value to object type (but not both)
dictBO = dictBB
dictOB = dictBB
dictBB = dictBO // expected-error{{cannot assign value of type 'Dictionary<BridgedToObjC, ObjC>' to type 'Dictionary<BridgedToObjC, BridgedToObjC>'}}
dictBB = dictOB // expected-error{{cannot assign value of type 'Dictionary<ObjC, BridgedToObjC>' to type 'Dictionary<BridgedToObjC, BridgedToObjC>'}}
dictDO = dictBB // expected-error{{cannot assign value of type 'Dictionary<BridgedToObjC, BridgedToObjC>' to type 'Dictionary<DerivesObjC, ObjC>'}}
dictOD = dictBB // expected-error{{cannot assign value of type 'Dictionary<BridgedToObjC, BridgedToObjC>' to type 'Dictionary<ObjC, DerivesObjC>'}}
dictDD = dictBB // expected-error{{cannot assign value of type 'Dictionary<BridgedToObjC, BridgedToObjC>' to type 'Dictionary<DerivesObjC, DerivesObjC>'}}
_ = dictDD; _ = dictDO; _ = dictOD; _ = dictOO; _ = dictOR; _ = dictOR; _ = dictRR; _ = dictRO
}
func testDowncastBridge() {
let dictRR = Dictionary<Root, Root>()
let dictRO = Dictionary<Root, ObjC>()
_ = Dictionary<ObjC, Root>()
_ = Dictionary<ObjC, ObjC>()
_ = Dictionary<ObjC, DerivesObjC>()
let dictDO = Dictionary<DerivesObjC, ObjC>()
_ = Dictionary<DerivesObjC, DerivesObjC>()
_ = Dictionary<BridgedToObjC, BridgedToObjC>()
let dictBO = Dictionary<BridgedToObjC, ObjC>()
let dictOB = Dictionary<ObjC, BridgedToObjC>()
// Downcast to bridged value types.
dictRR as! Dictionary<BridgedToObjC, BridgedToObjC>
dictRR as! Dictionary<BridgedToObjC, ObjC>
dictRR as! Dictionary<ObjC, BridgedToObjC>
dictRO as! Dictionary<BridgedToObjC, BridgedToObjC>
dictRO as! Dictionary<BridgedToObjC, ObjC>
dictRO as! Dictionary<ObjC, BridgedToObjC>
dictBO as! Dictionary<BridgedToObjC, BridgedToObjC>
dictOB as! Dictionary<BridgedToObjC, BridgedToObjC>
// We don't do mixed down/upcasts.
dictDO as! Dictionary<BridgedToObjC, BridgedToObjC> // expected-error{{'Dictionary<DerivesObjC, ObjC>' is not convertible to 'Dictionary<BridgedToObjC, BridgedToObjC>'}}
}
func testConditionalDowncastBridge() {
var dictRR = Dictionary<Root, Root>()
var dictRO = Dictionary<Root, ObjC>()
var dictOR = Dictionary<ObjC, Root>()
var dictOO = Dictionary<ObjC, ObjC>()
var dictOD = Dictionary<ObjC, DerivesObjC>()
var dictDO = Dictionary<DerivesObjC, ObjC>()
var dictDD = Dictionary<DerivesObjC, DerivesObjC>()
var dictBB = Dictionary<BridgedToObjC, BridgedToObjC>()
var dictBO = Dictionary<BridgedToObjC, ObjC>()
var dictOB = Dictionary<ObjC, BridgedToObjC>()
// Downcast to bridged value types.
if let d = dictRR as? Dictionary<BridgedToObjC, BridgedToObjC> { }
if let d = dictRR as? Dictionary<BridgedToObjC, ObjC> { }
if let d = dictRR as? Dictionary<ObjC, BridgedToObjC> { }
if let d = dictRO as? Dictionary<BridgedToObjC, BridgedToObjC> { }
if let d = dictRO as? Dictionary<BridgedToObjC, ObjC> { }
if let d = dictRO as? Dictionary<ObjC, BridgedToObjC> { }
if let d = dictBO as? Dictionary<BridgedToObjC, BridgedToObjC> { }
if let d = dictOB as? Dictionary<BridgedToObjC, BridgedToObjC> { }
// We don't do mixed down/upcasts.
if let d = dictDO as? Dictionary<BridgedToObjC, BridgedToObjC> { } // expected-error{{'Dictionary<DerivesObjC, ObjC>' is not convertible to 'Dictionary<BridgedToObjC, BridgedToObjC>'}}
}
|
apache-2.0
|
c4be1a67305eb39fe9f96e7ebd372b56
| 31.287582 | 186 | 0.707287 | 3.856362 | false | false | false | false |
tkremenek/swift
|
test/Constraints/result_builder_diags.swift
|
2
|
20203
|
// RUN: %target-typecheck-verify-swift -disable-availability-checking
enum Either<T,U> {
case first(T)
case second(U)
}
@resultBuilder
struct TupleBuilder { // expected-note 2 {{struct 'TupleBuilder' declared here}}
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: T1) -> T1 {
return t1
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
static func buildIf<T>(_ value: T?) -> T? { return value }
static func buildEither<T,U>(first value: T) -> Either<T,U> {
return .first(value)
}
static func buildEither<T,U>(second value: U) -> Either<T,U> {
return .second(value)
}
}
@resultBuilder
struct TupleBuilderWithoutIf { // expected-note 3{{struct 'TupleBuilderWithoutIf' declared here}}
// expected-note@-1{{add 'buildOptional(_:)' to the result builder 'TupleBuilderWithoutIf' to add support for 'if' statements without an 'else'}}
// expected-note@-2{{add 'buildEither(first:)' and 'buildEither(second:)' to the result builder 'TupleBuilderWithoutIf' to add support for 'if'-'else' and 'switch'}}
// expected-note@-3{{add 'buildArray(_:)' to the result builder 'TupleBuilderWithoutIf' to add support for 'for'..'in' loops}}
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: T1) -> T1 {
return t1
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
}
func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) {
print(body(cond))
}
func tuplifyWithoutIf<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) {
print(body(cond))
}
func testDiags() {
// For loop
tuplify(true) { _ in
17
for c in name {
// expected-error@-1 {{cannot find 'name' in scope}}
}
}
// Declarations
tuplify(true) { _ in
17
let x = 17
let y: Int // expected-error{{closure containing a declaration cannot be used with result builder 'TupleBuilder'}}
x + 25
}
// Statements unsupported by the particular builder.
tuplifyWithoutIf(true) {
if $0 { // expected-error{{closure containing control flow statement cannot be used with result builder 'TupleBuilderWithoutIf'}}
"hello"
}
}
tuplifyWithoutIf(true) {
if $0 { // expected-error{{closure containing control flow statement cannot be used with result builder 'TupleBuilderWithoutIf'}}
"hello"
} else {
}
}
tuplifyWithoutIf(true) { a in
for x in 0..<100 { // expected-error{{closure containing control flow statement cannot be used with result builder 'TupleBuilderWithoutIf'}}
x
}
}
}
struct A { }
struct B { }
func overloadedTuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) -> A { // expected-note {{found this candidate}}
return A()
}
func overloadedTuplify<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) -> B { // expected-note {{found this candidate}}
return B()
}
func testOverloading(name: String) {
let a1 = overloadedTuplify(true) { b in
if b {
"Hello, \(name)"
}
}
_ = overloadedTuplify(true) { cond in
if cond {
print(\"hello") // expected-error {{invalid component of Swift key path}}
}
}
let _: A = a1
_ = overloadedTuplify(true) { b in // expected-error {{ambiguous use of 'overloadedTuplify(_:body:)'}}
b ? "Hello, \(name)" : "Goodbye"
42
overloadedTuplify(false) {
$0 ? "Hello, \(name)" : "Goodbye"
42
if $0 {
"Hello, \(name)"
}
}
}
}
protocol P {
associatedtype T
}
struct AnyP : P {
typealias T = Any
init<T>(_: T) where T : P {}
}
struct TupleP<U> : P {
typealias T = U
init(_: U) {}
}
@resultBuilder
struct Builder {
static func buildBlock<S0, S1>(_ stmt1: S0, _ stmt2: S1) // expected-note {{required by static method 'buildBlock' where 'S1' = 'Label<_>.Type'}}
-> TupleP<(S0, S1)> where S0: P, S1: P {
return TupleP((stmt1, stmt2))
}
}
struct G<C> : P where C : P {
typealias T = C
init(@Builder _: () -> C) {}
}
struct Text : P {
typealias T = String
init(_: T) {}
}
struct Label<L> : P where L : P { // expected-note 2 {{'L' declared as parameter to type 'Label'}}
typealias T = L
init(@Builder _: () -> L) {} // expected-note {{'init(_:)' declared here}}
}
func test_51167632() -> some P {
AnyP(G { // expected-error {{type 'Label<_>.Type' cannot conform to 'P'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}}
Text("hello")
Label // expected-error {{generic parameter 'L' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{10-10=<<#L: P#>>}}
})
}
func test_56221372() -> some P {
AnyP(G {
Text("hello")
Label() // expected-error {{generic parameter 'L' could not be inferred}}
// expected-error@-1 {{missing argument for parameter #1 in call}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{10-10=<<#L: P#>>}}
})
}
struct SR11440 {
typealias ReturnsTuple<T> = () -> (T, T)
subscript<T, U>(@TupleBuilder x: ReturnsTuple<T>) -> (ReturnsTuple<U>) -> Void { //expected-note {{in call to 'subscript(_:)'}}
return { _ in }
}
func foo() {
// This is okay, we apply the result builder for the subscript arg.
self[{
5
5
}]({
(5, 5)
})
// But we shouldn't perform the transform for the argument to the call
// made on the function returned from the subscript.
self[{ // expected-error {{generic parameter 'U' could not be inferred}}
5
5
}]({
5
5
})
}
}
func acceptInt(_: Int, _: () -> Void) { }
// SR-11350 crash due to improper recontextualization.
func erroneousSR11350(x: Int) {
tuplify(true) { b in
17
x + 25
Optional(tuplify(false) { b in
if b {
acceptInt(0) { }
}
}).domap(0) // expected-error{{value of type '()?' has no member 'domap'}}
}
}
func extraArg() {
tuplify(true) { _ in
1
2
3
4
5
6 // expected-error {{extra argument in call}}
}
}
// rdar://problem/53209000 - use of #warning and #error
tuplify(true) { x in
1
#error("boom") // expected-error{{boom}}
"hello"
#warning("oops") // expected-warning{{oops}}
3.14159
}
struct MyTuplifiedStruct {
var condition: Bool
@TupleBuilder var computed: some Any { // expected-note{{remove the attribute to explicitly disable the result builder}}{{3-17=}}
if condition {
return 17 // expected-warning{{application of result builder 'TupleBuilder' disabled by explicit 'return' statement}}
// expected-note@-1{{remove 'return' statements to apply the result builder}}{{7-14=}}{{12-19=}}
} else {
return 42
}
}
}
func test_invalid_return_type_in_body() {
tuplify(true) { _ -> (Void, Int) in
tuplify(false) { condition in
if condition {
return 42 // expected-error {{cannot use explicit 'return' statement in the body of result builder 'TupleBuilder'}}
// expected-note@-1 {{remove 'return' statements to apply the result builder}} {{9-16=}}
} else {
1
}
}
42
}
}
// Check that we're performing syntactic use diagnostics.
func acceptMetatype<T>(_: T.Type) -> Bool { true }
func syntacticUses<T>(_: T) {
tuplify(true) { x in
if x && acceptMetatype(T) { // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}
acceptMetatype(T) // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}
}
}
}
// Check custom diagnostics within "if" conditions.
struct HasProperty {
var property: Bool = false
}
func checkConditions(cond: Bool) {
var x = HasProperty()
tuplify(cond) { value in
if x.property = value { // expected-error{{use of '=' in a boolean context, did you mean '=='?}}
"matched it"
}
}
}
// Check that a closure with a single "return" works with result builders.
func checkSingleReturn(cond: Bool) {
tuplify(cond) { value in
return (value, 17)
}
tuplify(cond) { value in
(value, 17)
}
tuplify(cond) {
($0, 17)
}
}
// rdar://problem/59116520
func checkImplicitSelfInClosure() {
@resultBuilder
struct Builder {
static func buildBlock(_ children: String...) -> Element { Element() }
}
struct Element {
static func nonEscapingClosure(@Builder closure: (() -> Element)) {}
static func escapingClosure(@Builder closure: @escaping (() -> Element)) {}
}
class C {
let identifier: String = ""
func testImplicitSelf() {
Element.nonEscapingClosure {
identifier // okay
}
Element.escapingClosure { // expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}}
identifier // expected-error {{reference to property 'identifier' in closure requires explicit use of 'self' to make capture semantics explicit}}
// expected-note@-1 {{reference 'self.' explicitly}}
}
}
}
}
// rdar://problem/59239224 - crash because some nodes don't have type
// information during solution application.
struct X<T> {
init(_: T) { }
}
@TupleBuilder func foo(cond: Bool) -> some Any {
if cond {
tuplify(cond) { x in
X(x)
}
}
}
// switch statements don't allow fallthrough
enum E {
case a
case b(Int, String?)
}
func testSwitch(e: E) {
tuplify(true) { c in
"testSwitch"
switch e {
case .a:
"a"
case .b(let i, let s?):
i * 2
s + "!"
fallthrough // expected-error{{closure containing control flow statement cannot be used with result builder 'TupleBuilder'}}
case .b(let i, nil):
"just \(i)"
}
}
}
// Ensure that we don't back-propagate constraints to the subject
// expression. This is a potential avenue for future exploration, but
// is currently not supported by switch statements outside of function
// builders. It's better to be consistent for now.
enum E2 {
case b(Int, String?) // expected-note{{'b' declared here}}
}
func getSomeEnumOverloaded(_: Double) -> E { return .a }
func getSomeEnumOverloaded(_: Int) -> E2 { return .b(0, nil) }
func testOverloadedSwitch() {
tuplify(true) { c in
// FIXME: Bad source location.
switch getSomeEnumOverloaded(17) { // expected-error{{type 'E2' has no member 'a'; did you mean 'b'?}}
case .a:
"a"
default:
"default"
}
}
}
// Check exhaustivity.
func testNonExhaustiveSwitch(e: E) {
tuplify(true) { c in
"testSwitch"
switch e { // expected-error{{switch must be exhaustive}}
// expected-note @-1{{add missing case: '.b(_, .none)'}}
case .a:
"a"
case .b(let i, let s?):
i * 2
s + "!"
}
}
}
// rdar://problem/59856491
struct TestConstraintGenerationErrors {
@TupleBuilder var buildTupleFnBody: String {
let a = nil // There is no diagnostic here because next line fails to pre-check, so body is invalid
String(nothing) // expected-error {{cannot find 'nothing' in scope}}
}
@TupleBuilder var nilWithoutContext: String {
let a = nil // expected-error {{'nil' requires a contextual type}}
""
}
func buildTupleClosure() {
tuplify(true) { _ in
let a = nothing // expected-error {{cannot find 'nothing' in scope}}
String(nothing)
}
}
}
// Check @unknown
func testUnknownInSwitchSwitch(e: E) {
tuplify(true) { c in
"testSwitch"
switch e {
case .b(let i, let s?):
i * 2
s + "!"
default:
"nothing"
@unknown case .a: // expected-error{{'@unknown' is only supported for catch-all cases ("case _")}}
// expected-error@-1{{'case' blocks cannot appear after the 'default' block of a 'switch'}}
"a"
}
}
tuplify(true) { c in
"testSwitch"
switch e {
@unknown case _: // expected-error{{'@unknown' can only be applied to the last case in a switch}}
"a"
default:
"default"
}
}
}
// Check for mutability mismatches when there are multiple case items
// referring to same-named variables.
enum E3 {
case a(Int, String)
case b(String, Int)
case c(String, Int)
}
func testCaseMutabilityMismatches(e: E3) {
tuplify(true) { c in
"testSwitch"
switch e {
case .a(let x, var y),
.b(let y, // expected-error{{'let' pattern binding must match previous 'var' pattern binding}}
var x), // expected-error{{'var' pattern binding must match previous 'let' pattern binding}}
.c(let y, // expected-error{{'let' pattern binding must match previous 'var' pattern binding}}
var x): // expected-error{{'var' pattern binding must match previous 'let' pattern binding}}
x
y += "a"
default:
"default"
}
}
}
// Check for type equivalence among different case variables with the same name.
func testCaseVarTypes(e: E3) {
// FIXME: Terrible diagnostic
tuplify(true) { c in // expected-error{{type of expression is ambiguous without more context}}
"testSwitch"
switch e {
case .a(let x, let y),
.c(let x, let y):
x
y + "a"
}
}
}
// Test for buildFinalResult.
@resultBuilder
struct WrapperBuilder {
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: T1) -> T1 {
return t1
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
static func buildIf<T>(_ value: T?) -> T? { return value }
static func buildEither<T,U>(first value: T) -> Either<T,U> {
return .first(value)
}
static func buildEither<T,U>(second value: U) -> Either<T,U> {
return .second(value)
}
static func buildFinalResult<T>(_ value: T) -> Wrapper<T> {
return Wrapper(value: value)
}
}
struct Wrapper<T> {
var value: T
}
func wrapperify<T>(_ cond: Bool, @WrapperBuilder body: (Bool) -> T) -> T{
return body(cond)
}
func testWrapperBuilder() {
let x = wrapperify(true) { c in
3.14159
"hello"
}
let _: Int = x // expected-error{{cannot convert value of type 'Wrapper<(Double, String)>' to specified type 'Int'}}
}
// rdar://problem/61347993 - empty result builder doesn't compile
func rdar61347993() {
struct Result {}
@resultBuilder
struct Builder {
static func buildBlock() -> Result {
Result()
}
}
func test_builder<T>(@Builder _: () -> T) {}
test_builder {} // Ok
func test_closure(_: () -> Result) {}
test_closure {} // expected-error {{cannot convert value of type '()' to closure result type 'Result'}}
}
// One-way constraints through parameters.
func wrapperifyInfer<T, U>(_ cond: Bool, @WrapperBuilder body: (U) -> T) -> T {
fatalError("boom")
}
let intValue = 17
wrapperifyInfer(true) { x in // expected-error{{unable to infer type of a closure parameter 'x' in the current context}}
intValue + x
}
struct DoesNotConform {}
struct MyView {
@TupleBuilder var value: some P { // expected-error {{return type of property 'value' requires that 'DoesNotConform' conform to 'P'}}
// expected-note@-1 {{opaque return type declared here}}
DoesNotConform()
}
@TupleBuilder func test() -> some P { // expected-error {{return type of instance method 'test()' requires that 'DoesNotConform' conform to 'P'}}
// expected-note@-1 {{opaque return type declared here}}
DoesNotConform()
}
@TupleBuilder var emptySwitch: some P {
switch Optional.some(1) { // expected-error {{'switch' statement body must have at least one 'case' or 'default' block; do you want to add a default case?}}
}
}
@TupleBuilder var invalidSwitchOne: some P {
switch Optional.some(1) {
case . // expected-error {{expected ':' after 'case'}}
} // expected-error {{expected identifier after '.' expression}}
}
@TupleBuilder var invalidSwitchMultiple: some P {
switch Optional.some(1) {
case .none: // expected-error {{'case' label in a 'switch' must have at least one executable statement}}
case . // expected-error {{expected ':' after 'case'}}
} // expected-error {{expected identifier after '.' expression}}
}
@TupleBuilder var invalidCaseWithoutDot: some P {
switch Optional.some(1) {
case none: 42 // expected-error {{cannot find 'none' in scope}}
case .some(let x):
0
}
}
@TupleBuilder var invalidConversion: Int { // expected-error {{cannot convert value of type 'String' to specified type 'Int'}}
""
}
}
// Make sure throwing result builder closures are implied.
enum MyError: Error {
case boom
}
do {
tuplify(true) { c in // expected-error{{invalid conversion from throwing function of type '(Bool) throws -> String' to non-throwing function type '(Bool) -> String'}}
"testThrow"
throw MyError.boom
}
}
struct TuplifiedStructWithInvalidClosure {
var condition: Bool
@TupleBuilder var unknownParameter: some Any {
if let cond = condition {
let _ = { (arg: UnknownType) in // expected-error {{cannot find type 'UnknownType' in scope}}
}
42
} else {
0
}
}
@TupleBuilder var unknownResult: some Any {
if let cond = condition {
let _ = { () -> UnknownType in // expected-error {{cannot find type 'UnknownType' in scope}}
}
42
} else {
0
}
}
@TupleBuilder var multipleLevelsDeep: some Any {
if let cond = condition {
switch MyError.boom {
case .boom:
let _ = { () -> UnknownType in // expected-error {{cannot find type 'UnknownType' in scope}}
}
}
42
} else {
0
}
}
@TupleBuilder var errorsDiagnosedByParser: some Any {
if let cond = condition {
tuplify { _ in
self. // expected-error {{expected member name following '.'}}
}
42
}
}
@TupleBuilder var nestedErrorsDiagnosedByParser: some Any {
tuplify(true) { _ in
tuplify { _ in
self. // expected-error {{expected member name following '.'}}
}
42
}
}
}
// rdar://65667992 - invalid case in enum causes fallback diagnostic
func test_rdar65667992() {
@resultBuilder
struct Builder {
static func buildBlock<T>(_ t: T) -> T { t }
static func buildEither<T>(first: T) -> T { first }
static func buildEither<T>(second: T) -> T { second }
}
struct S {}
enum E {
case set(v: Int, choices: [Int])
case notSet(choices: [Int])
}
struct MyView {
var entry: E
@Builder var body: S {
switch entry { // expected-error {{type 'E' has no member 'unset'}}
case .set(_, _): S()
case .unset(_): S()
default: S()
}
}
}
}
|
apache-2.0
|
2f021a1eaa6103f6d5fb6889bcdd1970
| 25.30599 | 173 | 0.609414 | 3.450555 | false | false | false | false |
zane001/ZMTuan
|
ZMTuan/View/Merchant/KindFilterCell.swift
|
1
|
2398
|
//
// KindFilterCell.swift
// ZMTuan
//
// Created by zm on 4/30/16.
// Copyright © 2016 zm. All rights reserved.
//
import UIKit
class KindFilterCell: UITableViewCell {
var imgView: UIImageView!
var nameLabel: UILabel!
var numberBtn: UIButton!
func initWithStyle(style: UITableViewCellStyle, reuseIdentifier: String?, withFrame frame: CGRect) -> AnyObject {
self.frame = frame
nameLabel = UILabel(frame: CGRectMake(10, 5, 100, 30))
nameLabel.font = UIFont.systemFontOfSize(15)
self.contentView.addSubview(nameLabel)
numberBtn = UIButton(type: .Custom)
numberBtn.frame = CGRectMake(self.frame.size.width-85, 12, 80, 15)
numberBtn.layer.masksToBounds = true
numberBtn.layer.cornerRadius = 7
numberBtn.titleLabel?.font = UIFont.systemFontOfSize(11)
numberBtn.setBackgroundImage(UIImage(named: "film"), forState: .Normal)
numberBtn.setBackgroundImage(UIImage(named: "film"), forState: .Highlighted)
numberBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
numberBtn.setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
self.contentView.addSubview(numberBtn)
let lineView: UIView = UIView(frame: CGRectMake(0, self.frame.size.height-0.5, self.frame.size.width, 0.5))
lineView.backgroundColor = RGB(0, g: 192, b: 192)
self.contentView.addSubview(lineView)
return self
}
func setGroupM(groupM: MerCateGroupModel) {
nameLabel.text = groupM.name
if groupM.list == nil {
numberBtn.setTitle("\(groupM.count)", forState: .Normal)
} else {
numberBtn.setTitle("\(groupM.count)>", forState: .Normal)
}
let str: NSString = "\(groupM.count)>"
let textSize = str.boundingRectWithSize(CGSizeMake(80, 15), options: NSStringDrawingOptions.UsesFontLeading, attributes: nil, context: nil)
numberBtn.frame = CGRectMake(self.frame.size.width-10-textSize.width-10, 12, textSize.width+10, 15)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
1b7ed7ad03abb243ad1c5958796eeda5
| 34.776119 | 147 | 0.651231 | 4.303411 | false | false | false | false |
Eonil/Editor
|
Editor4/DebugState.swift
|
1
|
2756
|
//
// DebugState.swift
// Editor4
//
// Created by Hoon H. on 2016/05/14.
// Copyright © 2016 Eonil. All rights reserved.
//
import Foundation.NSURL
import EonilToolbox
/// Reprents state of all debugging sessions.
///
/// This state is managed by `DebugService`. And the service notifies
/// its state to `Driver` by copy when it changes its state.
///
/// - Note:
/// A workspace can contain multiple debugging sessions.
///
struct DebugState {
var targets = [DebugTargetID: DebugTargetState]()
}
////////////////////////////////////////////////////////////////
struct DebugTargetID: Hashable {
private let oid = ObjectAddressID()
var hashValue: Int {
get { return oid.hashValue }
}
}
func == (a: DebugTargetID, b: DebugTargetID) -> Bool {
return a.oid == b.oid
}
struct DebugTargetState {
private(set) var executableURL: NSURL
var session: DebugProcessState?
}
struct DebugProcessState {
var processID: pid_t?
// var phase: DebugSessionPhase = .NotStarted
var threads = Transmissive<[DebugThreadState]>.none
var variables = Transmissive<DebugVariableState>.none
}
enum DebugProcessPhase {
case notStarted
case running
case paused(DebugSessionPauseReason)
case exited(DebugSessionExitReason)
}
enum DebugSessionPauseReason {
case breakpoint
case crash
case userCommand
}
enum DebugSessionExitReason {
case end(code: Int)
case crash
case userCommand
}
////////////////////////////////////////////////////////////////
struct DebugProcessID: Hashable {
var hashValue: Int {
get { MARK_unimplemented(); fatalError() }
}
}
func ==(a: DebugProcessID, b: DebugProcessID) -> Bool {
MARK_unimplemented()
return false
}
//struct DebugThreadID: Hashable {
// var hashValue: Int {
// get { MARK_unimplemented(); fatalError() }
// }
//}
//func ==(a: DebugThreadID, b: DebugThreadID) -> Bool {
// MARK_unimplemented()
// return false
//}
struct DebugThreadState {
var callStackFrames = [DebugCallStackFrameState]()
}
//struct DebugCallStackID: Hashable {
// var hashValue: Int {
// get { MARK_unimplemented(); fatalError() }
// }
//}
//func ==(a: DebugCallStackID, b: DebugCallStackID) -> Bool {
//
//}
struct DebugCallStackFrameState {
var functionName: String
}
////////////////////////////////////////////////////////////////
struct DebugVariableState {
var name: String
var type: String
var value: String
var subvariables = Progressive<(), [DebugVariableState]>.none
}
//enum DebugVariableLazySubvariables {
// case Unresolved
// case Resolved([DebugVariableState])
//}
//enum DebugVariableType {
//
//}
//enum DebugVariableValue {
// case
//}
|
mit
|
6f4e43fe78cf60a00978c52e83f1c32c
| 19.109489 | 69 | 0.624682 | 4.081481 | false | false | false | false |
timbodeit/RegexNamedCaptureGroups
|
RegexNamedCaptureGroups/Classes/GroupnameResolver.swift
|
1
|
1896
|
import unicode
import Regex
/**
Resolves a capture group's name to its index for a given regex.
To do this, GroupnameResolver calls into the ICU regex library,
that NSRegularExpression is based on.
*/
class GroupnameResolver {
private let uregex: COpaquePointer
init?(regex: NSRegularExpression) {
let cPattern = (regex.pattern as NSString).UTF8String
let flag = regex.options.uregexFlag
var errorCode = U_ZERO_ERROR
uregex = uregex_openC(cPattern, flag, nil, &errorCode)
if errorCode.isFailure {
return nil
}
}
func numberForCaptureGroupWithName(name: String) -> Int? {
let cName = (name as NSString).UTF8String
let nullTerminatedStringFlag: Int32 = -1
var errorCode = U_ZERO_ERROR
let groupNumber = uregex_groupNumberFromCName(uregex, cName, nullTerminatedStringFlag, &errorCode)
if errorCode.isSuccess {
return Int(groupNumber)
} else {
return nil
}
}
deinit {
uregex_close(uregex)
}
}
private extension UErrorCode {
var isSuccess: Bool {
return self.rawValue <= U_ZERO_ERROR.rawValue
}
var isFailure: Bool {
return self.rawValue > U_ZERO_ERROR.rawValue
}
}
private extension NSRegularExpressionOptions {
var uregexFlag: UInt32 {
var flag = 0 as UInt32
if self.contains(.CaseInsensitive) {
flag |= UREGEX_CASE_INSENSITIVE.rawValue
}
if self.contains(.AllowCommentsAndWhitespace) {
flag |= UREGEX_COMMENTS.rawValue
}
if self.contains(.DotMatchesLineSeparators) {
flag |= UREGEX_DOTALL.rawValue
}
if self.contains(.AnchorsMatchLines) {
flag |= UREGEX_MULTILINE.rawValue
}
if self.contains(.UseUnixLineSeparators) {
flag |= UREGEX_UNIX_LINES.rawValue
}
if self.contains(.UseUnicodeWordBoundaries) {
flag |= UREGEX_UWORD.rawValue
}
return flag
}
}
|
mit
|
bdffb1b486a1dd9f3d4a05104f25f1ff
| 23.307692 | 102 | 0.676688 | 3.983193 | false | false | false | false |
ihomway/RayWenderlichCourses
|
iOS Concurrency with GCD and Operations/Operations In Practice/TiltShift/TiltShift/NSData+Compression.swift
|
4
|
8313
|
/*
The MIT License (MIT)
Copyright (c) 2015 Lee Morgan
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 Foundation
import Compression
/** Available Compression Algorithms
- Compression.lz4 : Fast compression
- Compression.zlib : Balanced between speed and compression
- Compression.lzma : High compression
- Compression.lzfse : Apple-specific high performance compression. Faster and better compression than ZLIB, but slower than LZ4 and does not compress as well as LZMA.
*/
enum Compression {
/// Fast compression
case lz4
/// Balanced between speed and compression
case zlib
/// High compression
case lzma
/// Apple-specific high performance compression. Faster and better compression than ZLIB, but slower than LZ4 and does not compress as well as LZMA.
case lzfse
}
extension Data {
/// Returns a Data object initialized by decompressing the data from the file specified by `path`. Attempts to determine the appropriate decompression algorithm using the path's extension.
///
/// This method is equivalent to `Data(contentsOfArchive:usingCompression:)` with `nil compression`
///
/// let data = Data(contentsOfArchive: absolutePathToFile)
///
/// - Parameter contentsOfArchive: The absolute path of the file from which to read data
/// - Returns: A Data object initialized by decompressing the data from the file specified by `path`. Returns `nil` if decompression fails.
init?(contentsOfArchive path: String) {
self.init(contentsOfArchive: path, usedCompression: nil)
}
/// Returns a Data object initialized by decompressing the data from the file specified by `path` using the given `compression` algorithm.
///
/// let data = Data(contentsOfArchive: absolutePathToFile, usedCompression: Compression.lzfse)
///
/// - Parameter contentsOfArchive: The absolute path of the file from which to read data
/// - Parameter usedCompression: Algorithm to use during decompression. If compression is nil, attempts to determine the appropriate decompression algorithm using the path's extension
/// - Returns: A Data object initialized by decompressing the data from the file specified by `path` using the given `compression` algorithm. Returns `nil` if decompression fails.
init?(contentsOfArchive path: String, usedCompression: Compression?) {
let pathURL = URL(fileURLWithPath: path)
// read in the compressed data from disk
guard let compressedData = try? Data(contentsOf: pathURL) else {
return nil
}
// if compression is set use it
let compression: Compression
if usedCompression != nil {
compression = usedCompression!
}
else {
// otherwise, attempt to use the file extension to determine the compression algorithm
switch pathURL.pathExtension.lowercased() {
case "lz4" : compression = Compression.lz4
case "zlib" : compression = Compression.zlib
case "lzma" : compression = Compression.lzma
case "lzfse": compression = Compression.lzfse
default: return nil
}
}
// finally, attempt to uncompress the data and initalize self
if let uncompressedData = compressedData.uncompressed(using: compression) {
self = uncompressedData
}
else {
return nil
}
}
/// Returns a Data object created by compressing the receiver using the given compression algorithm.
///
/// let compressedData = someData.compressed(using: Compression.lzfse)
///
/// - Parameter using: Algorithm to use during compression
/// - Returns: A Data object created by encoding the receiver's contents using the provided compression algorithm. Returns nil if compression fails or if the receiver's length is 0.
func compressed(using compression: Compression) -> Data? {
return self.data(using: compression, operation: .encode)
}
/// Returns a Data object by uncompressing the receiver using the given compression algorithm.
///
/// let uncompressedData = someCompressedData.uncompressed(using: Compression.lzfse)
///
/// - Parameter using: Algorithm to use during decompression
/// - Returns: A Data object created by decoding the receiver's contents using the provided compression algorithm. Returns nil if decompression fails or if the receiver's length is 0.
func uncompressed(using compression: Compression) -> Data? {
return self.data(using: compression, operation: .decode)
}
private enum CompressionOperation {
case encode
case decode
}
private func data(using compression: Compression, operation: CompressionOperation) -> Data? {
guard self.count > 0 else {
return nil
}
let streamPtr = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
var stream = streamPtr.pointee
var status : compression_status
var op : compression_stream_operation
var flags : Int32
var algorithm : compression_algorithm
switch compression {
case .lz4:
algorithm = COMPRESSION_LZ4
case .lzfse:
algorithm = COMPRESSION_LZFSE
case .lzma:
algorithm = COMPRESSION_LZMA
case .zlib:
algorithm = COMPRESSION_ZLIB
}
switch operation {
case .encode:
op = COMPRESSION_STREAM_ENCODE
flags = Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
case .decode:
op = COMPRESSION_STREAM_DECODE
flags = 0
}
status = compression_stream_init(&stream, op, algorithm)
guard status != COMPRESSION_STATUS_ERROR else {
// an error occurred
return nil
}
let outputData = withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Data? in
// setup the stream's source
stream.src_ptr = bytes
stream.src_size = count
// setup the stream's output buffer
// we use a temporary buffer to store the data as it's compressed
let dstBufferSize : size_t = 4096
let dstBufferPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: dstBufferSize)
stream.dst_ptr = dstBufferPtr
stream.dst_size = dstBufferSize
// and we store the output in a mutable data object
var outputData = Data()
repeat {
status = compression_stream_process(&stream, flags)
switch status {
case COMPRESSION_STATUS_OK:
// Going to call _process at least once more, so prepare for that
if stream.dst_size == 0 {
// Output buffer full...
// Write out to outputData
outputData.append(dstBufferPtr, count: dstBufferSize)
// Re-use dstBuffer
stream.dst_ptr = dstBufferPtr
stream.dst_size = dstBufferSize
}
case COMPRESSION_STATUS_END:
// We are done, just write out the output buffer if there's anything in it
if stream.dst_ptr > dstBufferPtr {
outputData.append(dstBufferPtr, count: stream.dst_ptr - dstBufferPtr)
}
case COMPRESSION_STATUS_ERROR:
return nil
default:
break
}
} while status == COMPRESSION_STATUS_OK
return outputData
}
compression_stream_destroy(&stream)
return outputData
}
}
|
mit
|
892b487acbcbff81600e345da475e9d5
| 36.111607 | 190 | 0.690605 | 4.841584 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.